secretsmanager_test.go 7.6 KB

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