secretsmanager_test.go 10 KB

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