secretsmanager_test.go 11 KB

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