secretsmanager_test.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  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. // for testing caching
  35. expectedCounter *int
  36. }
  37. func makeValidSecretsManagerTestCase() *secretsManagerTestCase {
  38. smtc := secretsManagerTestCase{
  39. fakeClient: fakesm.NewClient(),
  40. apiInput: makeValidAPIInput(),
  41. remoteRef: makeValidRemoteRef(),
  42. apiOutput: makeValidAPIOutput(),
  43. apiErr: nil,
  44. expectError: "",
  45. expectedSecret: "",
  46. expectedData: map[string][]byte{},
  47. }
  48. smtc.fakeClient.WithValue(smtc.apiInput, smtc.apiOutput, smtc.apiErr)
  49. return &smtc
  50. }
  51. func makeValidRemoteRef() *esv1alpha1.ExternalSecretDataRemoteRef {
  52. return &esv1alpha1.ExternalSecretDataRemoteRef{
  53. Key: "/baz",
  54. Version: "AWSCURRENT",
  55. }
  56. }
  57. func makeValidAPIInput() *awssm.GetSecretValueInput {
  58. return &awssm.GetSecretValueInput{
  59. SecretId: aws.String("/baz"),
  60. VersionStage: aws.String("AWSCURRENT"),
  61. }
  62. }
  63. func makeValidAPIOutput() *awssm.GetSecretValueOutput {
  64. return &awssm.GetSecretValueOutput{
  65. SecretString: aws.String(""),
  66. }
  67. }
  68. func makeValidSecretsManagerTestCaseCustom(tweaks ...func(smtc *secretsManagerTestCase)) *secretsManagerTestCase {
  69. smtc := makeValidSecretsManagerTestCase()
  70. for _, fn := range tweaks {
  71. fn(smtc)
  72. }
  73. smtc.fakeClient.WithValue(smtc.apiInput, smtc.apiOutput, smtc.apiErr)
  74. return smtc
  75. }
  76. // This case can be shared by both GetSecret and GetSecretMap tests.
  77. // bad case: set apiErr.
  78. var setAPIErr = func(smtc *secretsManagerTestCase) {
  79. smtc.apiErr = fmt.Errorf("oh no")
  80. smtc.expectError = "oh no"
  81. }
  82. // test the sm<->aws interface
  83. // make sure correct values are passed and errors are handled accordingly.
  84. func TestSecretsManagerGetSecret(t *testing.T) {
  85. // good case: default version is set
  86. // key is passed in, output is sent back
  87. setSecretString := func(smtc *secretsManagerTestCase) {
  88. smtc.apiOutput.SecretString = aws.String("testtesttest")
  89. smtc.expectedSecret = "testtesttest"
  90. }
  91. // good case: extract property
  92. // Testing that the property exists in the SecretString
  93. setRemoteRefPropertyExistsInKey := func(smtc *secretsManagerTestCase) {
  94. smtc.remoteRef.Property = "/shmoo"
  95. smtc.apiOutput.SecretString = aws.String(`{"/shmoo": "bang"}`)
  96. smtc.expectedSecret = "bang"
  97. }
  98. // bad case: missing property
  99. setRemoteRefMissingProperty := func(smtc *secretsManagerTestCase) {
  100. smtc.remoteRef.Property = "INVALPROP"
  101. smtc.expectError = "key INVALPROP does not exist in secret"
  102. }
  103. // bad case: extract property failure due to invalid json
  104. setRemoteRefMissingPropertyInvalidJSON := func(smtc *secretsManagerTestCase) {
  105. smtc.remoteRef.Property = "INVALPROP"
  106. smtc.apiOutput.SecretString = aws.String(`------`)
  107. smtc.expectError = "key INVALPROP does not exist in secret"
  108. }
  109. // good case: set .SecretString to nil but set binary with value
  110. setSecretBinaryNotSecretString := func(smtc *secretsManagerTestCase) {
  111. smtc.apiOutput.SecretBinary = []byte("yesplease")
  112. // needs to be set as nil, empty quotes ("") is considered existing
  113. smtc.apiOutput.SecretString = nil
  114. smtc.expectedSecret = "yesplease"
  115. }
  116. // bad case: both .SecretString and .SecretBinary are nil
  117. setSecretBinaryAndSecretStringToNil := func(smtc *secretsManagerTestCase) {
  118. smtc.apiOutput.SecretBinary = nil
  119. smtc.apiOutput.SecretString = nil
  120. smtc.expectError = "no secret string nor binary for key"
  121. }
  122. // good case: secretOut.SecretBinary JSON parsing
  123. setNestedSecretValueJSONParsing := func(smtc *secretsManagerTestCase) {
  124. smtc.apiOutput.SecretString = nil
  125. smtc.apiOutput.SecretBinary = []byte(`{"foobar":{"baz":"nestedval"}}`)
  126. smtc.remoteRef.Property = "foobar.baz"
  127. smtc.expectedSecret = "nestedval"
  128. }
  129. // good case: custom version set
  130. setCustomVersion := func(smtc *secretsManagerTestCase) {
  131. smtc.apiInput.VersionStage = aws.String("1234")
  132. smtc.remoteRef.Version = "1234"
  133. smtc.apiOutput.SecretString = aws.String("FOOBA!")
  134. smtc.expectedSecret = "FOOBA!"
  135. }
  136. successCases := []*secretsManagerTestCase{
  137. makeValidSecretsManagerTestCase(),
  138. makeValidSecretsManagerTestCaseCustom(setSecretString),
  139. makeValidSecretsManagerTestCaseCustom(setRemoteRefPropertyExistsInKey),
  140. makeValidSecretsManagerTestCaseCustom(setRemoteRefMissingProperty),
  141. makeValidSecretsManagerTestCaseCustom(setRemoteRefMissingPropertyInvalidJSON),
  142. makeValidSecretsManagerTestCaseCustom(setSecretBinaryNotSecretString),
  143. makeValidSecretsManagerTestCaseCustom(setSecretBinaryAndSecretStringToNil),
  144. makeValidSecretsManagerTestCaseCustom(setNestedSecretValueJSONParsing),
  145. makeValidSecretsManagerTestCaseCustom(setCustomVersion),
  146. makeValidSecretsManagerTestCaseCustom(setAPIErr),
  147. }
  148. for k, v := range successCases {
  149. sm := SecretsManager{
  150. cache: make(map[string]*awssm.GetSecretValueOutput),
  151. client: v.fakeClient,
  152. }
  153. out, err := sm.GetSecret(context.Background(), *v.remoteRef)
  154. if !ErrorContains(err, v.expectError) {
  155. t.Errorf("[%d] unexpected error: %s, expected: '%s'", k, err.Error(), v.expectError)
  156. }
  157. if err == nil && string(out) != v.expectedSecret {
  158. t.Errorf("[%d] unexpected secret: expected %s, got %s", k, v.expectedSecret, string(out))
  159. }
  160. }
  161. }
  162. func TestCaching(t *testing.T) {
  163. fakeClient := fakesm.NewClient()
  164. // good case: first call, since we are using the same key, results should be cached and the counter should not go
  165. // over 1
  166. firstCall := func(smtc *secretsManagerTestCase) {
  167. smtc.apiOutput.SecretString = aws.String(`{"foo":"bar", "bar":"vodka"}`)
  168. smtc.remoteRef.Property = "foo"
  169. smtc.expectedSecret = "bar"
  170. smtc.expectedCounter = aws.Int(1)
  171. smtc.fakeClient = fakeClient
  172. }
  173. secondCall := func(smtc *secretsManagerTestCase) {
  174. smtc.apiOutput.SecretString = aws.String(`{"foo":"bar", "bar":"vodka"}`)
  175. smtc.remoteRef.Property = "bar"
  176. smtc.expectedSecret = "vodka"
  177. smtc.expectedCounter = aws.Int(1)
  178. smtc.fakeClient = fakeClient
  179. }
  180. notCachedCall := func(smtc *secretsManagerTestCase) {
  181. smtc.apiOutput.SecretString = aws.String(`{"sheldon":"bazinga", "bar":"foo"}`)
  182. smtc.remoteRef.Property = "sheldon"
  183. smtc.expectedSecret = "bazinga"
  184. smtc.expectedCounter = aws.Int(2)
  185. smtc.fakeClient = fakeClient
  186. smtc.apiInput.SecretId = aws.String("xyz")
  187. smtc.remoteRef.Key = "xyz" // it should reset the cache since the key is different
  188. }
  189. cachedCases := []*secretsManagerTestCase{
  190. makeValidSecretsManagerTestCaseCustom(firstCall),
  191. makeValidSecretsManagerTestCaseCustom(firstCall),
  192. makeValidSecretsManagerTestCaseCustom(secondCall),
  193. makeValidSecretsManagerTestCaseCustom(notCachedCall),
  194. }
  195. sm := SecretsManager{
  196. cache: make(map[string]*awssm.GetSecretValueOutput),
  197. }
  198. for k, v := range cachedCases {
  199. sm.client = v.fakeClient
  200. out, err := sm.GetSecret(context.Background(), *v.remoteRef)
  201. if !ErrorContains(err, v.expectError) {
  202. t.Errorf("[%d] unexpected error: %s, expected: '%s'", k, err.Error(), v.expectError)
  203. }
  204. if err == nil && string(out) != v.expectedSecret {
  205. t.Errorf("[%d] unexpected secret: expected %s, got %s", k, v.expectedSecret, string(out))
  206. }
  207. if v.expectedCounter != nil && v.fakeClient.ExecutionCounter != *v.expectedCounter {
  208. t.Errorf("[%d] unexpected counter value: expected %d, got %d", k, v.expectedCounter, v.fakeClient.ExecutionCounter)
  209. }
  210. }
  211. }
  212. func TestGetSecretMap(t *testing.T) {
  213. // good case: default version & deserialization
  214. setDeserialization := func(smtc *secretsManagerTestCase) {
  215. smtc.apiOutput.SecretString = aws.String(`{"foo":"bar"}`)
  216. smtc.expectedData["foo"] = []byte("bar")
  217. }
  218. // good case: caching
  219. cachedMap := func(smtc *secretsManagerTestCase) {
  220. smtc.apiOutput.SecretString = aws.String(`{"foo":"bar", "plus": "one"}`)
  221. smtc.expectedData["foo"] = []byte("bar")
  222. smtc.expectedData["plus"] = []byte("one")
  223. smtc.expectedCounter = aws.Int(1)
  224. }
  225. // bad case: invalid json
  226. setInvalidJSON := func(smtc *secretsManagerTestCase) {
  227. smtc.apiOutput.SecretString = aws.String(`-----------------`)
  228. smtc.expectError = "unable to unmarshal secret"
  229. }
  230. successCases := []*secretsManagerTestCase{
  231. makeValidSecretsManagerTestCaseCustom(setDeserialization),
  232. makeValidSecretsManagerTestCaseCustom(setAPIErr),
  233. makeValidSecretsManagerTestCaseCustom(setInvalidJSON),
  234. makeValidSecretsManagerTestCaseCustom(cachedMap),
  235. }
  236. for k, v := range successCases {
  237. sm := SecretsManager{
  238. cache: make(map[string]*awssm.GetSecretValueOutput),
  239. client: v.fakeClient,
  240. }
  241. out, err := sm.GetSecretMap(context.Background(), *v.remoteRef)
  242. if !ErrorContains(err, v.expectError) {
  243. t.Errorf("[%d] unexpected error: %s, expected: '%s'", k, err.Error(), v.expectError)
  244. }
  245. if err == nil && !cmp.Equal(out, v.expectedData) {
  246. t.Errorf("[%d] unexpected secret data: expected %#v, got %#v", k, v.expectedData, out)
  247. }
  248. if v.expectedCounter != nil && v.fakeClient.ExecutionCounter != *v.expectedCounter {
  249. t.Errorf("[%d] unexpected counter value: expected %d, got %d", k, v.expectedCounter, v.fakeClient.ExecutionCounter)
  250. }
  251. }
  252. }
  253. func ErrorContains(out error, want string) bool {
  254. if out == nil {
  255. return want == ""
  256. }
  257. if want == "" {
  258. return false
  259. }
  260. return strings.Contains(out.Error(), want)
  261. }