secretsmanager_test.go 10 KB

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