secretsmanager_test.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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. ref *esv1alpha1.ExternalSecretDataRemoteRef
  38. apiErr error
  39. expectError string
  40. expectedSecret string
  41. }
  42. func makeValidSecretsManagerTestCase() *secretsManagerTestCase {
  43. smtc := secretsManagerTestCase{
  44. fakeClient: &fakesm.Client{},
  45. apiInput: makeValidAPIInput(),
  46. ref: makeValidRef(),
  47. apiOutput: makeValidAPIOutput(),
  48. apiErr: nil,
  49. expectError: "",
  50. expectedSecret: "",
  51. }
  52. smtc.fakeClient.WithValue(smtc.apiInput, smtc.apiOutput, smtc.apiErr)
  53. return &smtc
  54. }
  55. func makeValidRef() *esv1alpha1.ExternalSecretDataRemoteRef {
  56. return &esv1alpha1.ExternalSecretDataRemoteRef{
  57. Key: "/baz",
  58. Version: "AWSCURRENT",
  59. }
  60. }
  61. func makeValidAPIInput() *awssm.GetSecretValueInput {
  62. return &awssm.GetSecretValueInput{
  63. SecretId: aws.String("/baz"),
  64. VersionStage: aws.String("AWSCURRENT"),
  65. }
  66. }
  67. func makeValidAPIOutput() *awssm.GetSecretValueOutput {
  68. return &awssm.GetSecretValueOutput{
  69. SecretString: aws.String(""),
  70. }
  71. }
  72. func makeValidSecretsManagerTestCaseCustom(tweaks ...func(smtc *secretsManagerTestCase)) *secretsManagerTestCase {
  73. smtc := makeValidSecretsManagerTestCase()
  74. for _, fn := range tweaks {
  75. fn(smtc)
  76. }
  77. smtc.fakeClient.WithValue(smtc.apiInput, smtc.apiOutput, smtc.apiErr)
  78. return smtc
  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. setRefPropertyExistsInKey := func(smtc *secretsManagerTestCase) {
  92. smtc.ref.Property = "/shmoo"
  93. smtc.apiOutput.SecretString = aws.String(`{"/shmoo": "bang"}`)
  94. smtc.expectedSecret = "bang"
  95. }
  96. // bad case: missing property
  97. setRefMissingProperty := func(smtc *secretsManagerTestCase) {
  98. smtc.ref.Property = "INVALPROP"
  99. smtc.expectError = "key INVALPROP does not exist in secret"
  100. }
  101. // bad case: extract property failure due to invalid json
  102. setRefMissingPropertyInvalidJSON := func(smtc *secretsManagerTestCase) {
  103. smtc.ref.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.ref.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.ref.Version = "1234"
  131. smtc.apiOutput.SecretString = aws.String("FOOBA!")
  132. smtc.expectedSecret = "FOOBA!"
  133. }
  134. // bad case: set apiErr
  135. setAPIErr := func(smtc *secretsManagerTestCase) {
  136. smtc.apiErr = fmt.Errorf("oh no")
  137. smtc.expectError = "oh no"
  138. }
  139. successCases := []*secretsManagerTestCase{
  140. makeValidSecretsManagerTestCase(),
  141. makeValidSecretsManagerTestCaseCustom(setSecretString),
  142. makeValidSecretsManagerTestCaseCustom(setRefPropertyExistsInKey),
  143. makeValidSecretsManagerTestCaseCustom(setRefMissingProperty),
  144. makeValidSecretsManagerTestCaseCustom(setRefMissingPropertyInvalidJSON),
  145. makeValidSecretsManagerTestCaseCustom(setSecretBinaryNotSecretString),
  146. makeValidSecretsManagerTestCaseCustom(setSecretBinaryAndSecretStringToNil),
  147. makeValidSecretsManagerTestCaseCustom(setNestedSecretValueJSONParsing),
  148. makeValidSecretsManagerTestCaseCustom(setCustomVersion),
  149. makeValidSecretsManagerTestCaseCustom(setAPIErr),
  150. }
  151. sm := SecretsManager{}
  152. for k, v := range successCases {
  153. sm.client = v.fakeClient
  154. out, err := sm.GetSecret(context.Background(), *v.ref)
  155. if !ErrorContains(err, v.expectError) {
  156. t.Errorf("[%d] unexpected error: %s, expected: '%s'", k, err.Error(), v.expectError)
  157. }
  158. if string(out) != v.expectedSecret {
  159. t.Errorf("[%d] unexpected secret: expected %s, got %s", k, v.expectedSecret, string(out))
  160. }
  161. }
  162. }
  163. func TestGetSecretMap(t *testing.T) {
  164. fake := &fakesm.Client{}
  165. p := &SecretsManager{
  166. client: fake,
  167. }
  168. for i, row := range []struct {
  169. apiInput *awssm.GetSecretValueInput
  170. apiOutput *awssm.GetSecretValueOutput
  171. rr esv1alpha1.ExternalSecretDataRemoteRef
  172. expectedData map[string]string
  173. apiErr error
  174. expectError string
  175. }{
  176. {
  177. // good case: default version & deserialization
  178. apiInput: &awssm.GetSecretValueInput{
  179. SecretId: aws.String("/baz"),
  180. VersionStage: aws.String("AWSCURRENT"),
  181. },
  182. apiOutput: &awssm.GetSecretValueOutput{
  183. SecretString: aws.String(`{"foo":"bar"}`),
  184. },
  185. rr: esv1alpha1.ExternalSecretDataRemoteRef{
  186. Key: "/baz",
  187. },
  188. expectedData: map[string]string{
  189. "foo": "bar",
  190. },
  191. apiErr: nil,
  192. expectError: "",
  193. },
  194. {
  195. // bad case: api error returned
  196. apiInput: &awssm.GetSecretValueInput{
  197. SecretId: aws.String("/baz"),
  198. VersionStage: aws.String("AWSCURRENT"),
  199. },
  200. apiOutput: &awssm.GetSecretValueOutput{
  201. SecretString: aws.String(`{"foo":"bar"}`),
  202. },
  203. rr: esv1alpha1.ExternalSecretDataRemoteRef{
  204. Key: "/baz",
  205. },
  206. expectedData: map[string]string{
  207. "foo": "bar",
  208. },
  209. apiErr: fmt.Errorf("some api err"),
  210. expectError: "some api err",
  211. },
  212. {
  213. // bad case: invalid json
  214. apiInput: &awssm.GetSecretValueInput{
  215. SecretId: aws.String("/baz"),
  216. VersionStage: aws.String("AWSCURRENT"),
  217. },
  218. apiOutput: &awssm.GetSecretValueOutput{
  219. SecretString: aws.String(`-----------------`),
  220. },
  221. rr: esv1alpha1.ExternalSecretDataRemoteRef{
  222. Key: "/baz",
  223. },
  224. expectedData: map[string]string{},
  225. apiErr: nil,
  226. expectError: "unable to unmarshal secret",
  227. },
  228. } {
  229. fake.WithValue(row.apiInput, row.apiOutput, row.apiErr)
  230. out, err := p.GetSecretMap(context.Background(), row.rr)
  231. if !ErrorContains(err, row.expectError) {
  232. t.Errorf("[%d] unexpected error: %s, expected: '%s'", i, err.Error(), row.expectError)
  233. }
  234. if cmp.Equal(out, row.expectedData) {
  235. t.Errorf("[%d] unexpected secret data: expected %#v, got %#v", i, row.expectedData, out)
  236. }
  237. }
  238. }
  239. func ErrorContains(out error, want string) bool {
  240. if out == nil {
  241. return want == ""
  242. }
  243. if want == "" {
  244. return false
  245. }
  246. return strings.Contains(out.Error(), want)
  247. }