secretsmanager_test.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  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 secretsmanager
  13. import (
  14. "context"
  15. "fmt"
  16. "strings"
  17. "testing"
  18. "github.com/aws/aws-sdk-go/aws"
  19. awssm "github.com/aws/aws-sdk-go/service/secretsmanager"
  20. "github.com/google/go-cmp/cmp"
  21. esv1alpha1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1alpha1"
  22. fakesm "github.com/external-secrets/external-secrets/pkg/provider/aws/secretsmanager/fake"
  23. )
  24. type secretsManagerTestCase struct {
  25. fakeClient *fakesm.Client
  26. apiInput *awssm.GetSecretValueInput
  27. apiOutput *awssm.GetSecretValueOutput
  28. remoteRef *esv1alpha1.ExternalSecretDataRemoteRef
  29. apiErr error
  30. expectError string
  31. expectedSecret string
  32. // for testing secretmap
  33. expectedData map[string][]byte
  34. }
  35. func makeValidSecretsManagerTestCase() *secretsManagerTestCase {
  36. smtc := secretsManagerTestCase{
  37. fakeClient: &fakesm.Client{},
  38. apiInput: makeValidAPIInput(),
  39. remoteRef: makeValidRemoteRef(),
  40. apiOutput: makeValidAPIOutput(),
  41. apiErr: nil,
  42. expectError: "",
  43. expectedSecret: "",
  44. expectedData: map[string][]byte{},
  45. }
  46. smtc.fakeClient.WithValue(smtc.apiInput, smtc.apiOutput, smtc.apiErr)
  47. return &smtc
  48. }
  49. func makeValidRemoteRef() *esv1alpha1.ExternalSecretDataRemoteRef {
  50. return &esv1alpha1.ExternalSecretDataRemoteRef{
  51. Key: "/baz",
  52. Version: "AWSCURRENT",
  53. }
  54. }
  55. func makeValidAPIInput() *awssm.GetSecretValueInput {
  56. return &awssm.GetSecretValueInput{
  57. SecretId: aws.String("/baz"),
  58. VersionStage: aws.String("AWSCURRENT"),
  59. }
  60. }
  61. func makeValidAPIOutput() *awssm.GetSecretValueOutput {
  62. return &awssm.GetSecretValueOutput{
  63. SecretString: aws.String(""),
  64. }
  65. }
  66. func makeValidSecretsManagerTestCaseCustom(tweaks ...func(smtc *secretsManagerTestCase)) *secretsManagerTestCase {
  67. smtc := makeValidSecretsManagerTestCase()
  68. for _, fn := range tweaks {
  69. fn(smtc)
  70. }
  71. smtc.fakeClient.WithValue(smtc.apiInput, smtc.apiOutput, smtc.apiErr)
  72. return smtc
  73. }
  74. // This case can be shared by both GetSecret and GetSecretMap tests.
  75. // bad case: set apiErr.
  76. var setAPIErr = func(smtc *secretsManagerTestCase) {
  77. smtc.apiErr = fmt.Errorf("oh no")
  78. smtc.expectError = "oh no"
  79. }
  80. // test the sm<->aws interface
  81. // make sure correct values are passed and errors are handled accordingly.
  82. func TestSecretsManagerGetSecret(t *testing.T) {
  83. // good case: default version is set
  84. // key is passed in, output is sent back
  85. setSecretString := func(smtc *secretsManagerTestCase) {
  86. smtc.apiOutput.SecretString = aws.String("testtesttest")
  87. smtc.expectedSecret = "testtesttest"
  88. }
  89. // good case: extract property
  90. // Testing that the property exists in the SecretString
  91. setRemoteRefPropertyExistsInKey := func(smtc *secretsManagerTestCase) {
  92. smtc.remoteRef.Property = "/shmoo"
  93. smtc.apiOutput.SecretString = aws.String(`{"/shmoo": "bang"}`)
  94. smtc.expectedSecret = "bang"
  95. }
  96. // bad case: missing property
  97. setRemoteRefMissingProperty := func(smtc *secretsManagerTestCase) {
  98. smtc.remoteRef.Property = "INVALPROP"
  99. smtc.expectError = "key INVALPROP does not exist in secret"
  100. }
  101. // bad case: extract property failure due to invalid json
  102. setRemoteRefMissingPropertyInvalidJSON := func(smtc *secretsManagerTestCase) {
  103. smtc.remoteRef.Property = "INVALPROP"
  104. smtc.apiOutput.SecretString = aws.String(`------`)
  105. smtc.expectError = "key INVALPROP does not exist in secret"
  106. }
  107. // good case: set .SecretString to nil but set binary with value
  108. setSecretBinaryNotSecretString := func(smtc *secretsManagerTestCase) {
  109. smtc.apiOutput.SecretBinary = []byte("yesplease")
  110. // needs to be set as nil, empty quotes ("") is considered existing
  111. smtc.apiOutput.SecretString = nil
  112. smtc.expectedSecret = "yesplease"
  113. }
  114. // bad case: both .SecretString and .SecretBinary are nil
  115. setSecretBinaryAndSecretStringToNil := func(smtc *secretsManagerTestCase) {
  116. smtc.apiOutput.SecretBinary = nil
  117. smtc.apiOutput.SecretString = nil
  118. smtc.expectError = "no secret string nor binary for key"
  119. }
  120. // good case: secretOut.SecretBinary JSON parsing
  121. setNestedSecretValueJSONParsing := func(smtc *secretsManagerTestCase) {
  122. smtc.apiOutput.SecretString = nil
  123. smtc.apiOutput.SecretBinary = []byte(`{"foobar":{"baz":"nestedval"}}`)
  124. smtc.remoteRef.Property = "foobar.baz"
  125. smtc.expectedSecret = "nestedval"
  126. }
  127. // good case: custom version set
  128. setCustomVersion := func(smtc *secretsManagerTestCase) {
  129. smtc.apiInput.VersionStage = aws.String("1234")
  130. smtc.remoteRef.Version = "1234"
  131. smtc.apiOutput.SecretString = aws.String("FOOBA!")
  132. smtc.expectedSecret = "FOOBA!"
  133. }
  134. successCases := []*secretsManagerTestCase{
  135. makeValidSecretsManagerTestCase(),
  136. makeValidSecretsManagerTestCaseCustom(setSecretString),
  137. makeValidSecretsManagerTestCaseCustom(setRemoteRefPropertyExistsInKey),
  138. makeValidSecretsManagerTestCaseCustom(setRemoteRefMissingProperty),
  139. makeValidSecretsManagerTestCaseCustom(setRemoteRefMissingPropertyInvalidJSON),
  140. makeValidSecretsManagerTestCaseCustom(setSecretBinaryNotSecretString),
  141. makeValidSecretsManagerTestCaseCustom(setSecretBinaryAndSecretStringToNil),
  142. makeValidSecretsManagerTestCaseCustom(setNestedSecretValueJSONParsing),
  143. makeValidSecretsManagerTestCaseCustom(setCustomVersion),
  144. makeValidSecretsManagerTestCaseCustom(setAPIErr),
  145. }
  146. sm := SecretsManager{}
  147. for k, v := range successCases {
  148. sm.client = v.fakeClient
  149. out, err := sm.GetSecret(context.Background(), *v.remoteRef)
  150. if !ErrorContains(err, v.expectError) {
  151. t.Errorf("[%d] unexpected error: %s, expected: '%s'", k, err.Error(), v.expectError)
  152. }
  153. if err == nil && string(out) != v.expectedSecret {
  154. t.Errorf("[%d] unexpected secret: expected %s, got %s", k, v.expectedSecret, string(out))
  155. }
  156. }
  157. }
  158. func TestGetSecretMap(t *testing.T) {
  159. // good case: default version & deserialization
  160. setDeserialization := func(smtc *secretsManagerTestCase) {
  161. smtc.apiOutput.SecretString = aws.String(`{"foo":"bar"}`)
  162. smtc.expectedData["foo"] = []byte("bar")
  163. }
  164. // bad case: invalid json
  165. setInvalidJSON := func(smtc *secretsManagerTestCase) {
  166. smtc.apiOutput.SecretString = aws.String(`-----------------`)
  167. smtc.expectError = "unable to unmarshal secret"
  168. }
  169. successCases := []*secretsManagerTestCase{
  170. makeValidSecretsManagerTestCaseCustom(setDeserialization),
  171. makeValidSecretsManagerTestCaseCustom(setAPIErr),
  172. makeValidSecretsManagerTestCaseCustom(setInvalidJSON),
  173. }
  174. sm := SecretsManager{}
  175. for k, v := range successCases {
  176. sm.client = v.fakeClient
  177. out, err := sm.GetSecretMap(context.Background(), *v.remoteRef)
  178. if !ErrorContains(err, v.expectError) {
  179. t.Errorf("[%d] unexpected error: %s, expected: '%s'", k, err.Error(), v.expectError)
  180. }
  181. if err == nil && !cmp.Equal(out, v.expectedData) {
  182. t.Errorf("[%d] unexpected secret data: expected %#v, got %#v", k, v.expectedData, out)
  183. }
  184. }
  185. }
  186. func ErrorContains(out error, want string) bool {
  187. if out == nil {
  188. return want == ""
  189. }
  190. if want == "" {
  191. return false
  192. }
  193. return strings.Contains(out.Error(), want)
  194. }