secretsmanager_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  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. esv1beta1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1beta1"
  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 *esv1beta1.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() *esv1beta1.ExternalSecretDataRemoteRef {
  53. return &esv1beta1.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: secretOut.SecretBinary no JSON parsing if name on key
  131. setSecretValueWithDot := func(smtc *secretsManagerTestCase) {
  132. smtc.apiOutput.SecretString = nil
  133. smtc.apiOutput.SecretBinary = []byte(`{"foobar.baz":"nestedval"}`)
  134. smtc.remoteRef.Property = "foobar.baz"
  135. smtc.expectedSecret = "nestedval"
  136. }
  137. // good case: custom version stage set
  138. setCustomVersionStage := func(smtc *secretsManagerTestCase) {
  139. smtc.apiInput.VersionStage = aws.String("1234")
  140. smtc.remoteRef.Version = "1234"
  141. smtc.apiOutput.SecretString = aws.String("FOOBA!")
  142. smtc.expectedSecret = "FOOBA!"
  143. }
  144. // good case: custom version id set
  145. setCustomVersionID := func(smtc *secretsManagerTestCase) {
  146. smtc.apiInput.VersionStage = nil
  147. smtc.apiInput.VersionId = aws.String("1234-5678")
  148. smtc.remoteRef.Version = "uuid/1234-5678"
  149. smtc.apiOutput.SecretString = aws.String("myvalue")
  150. smtc.expectedSecret = "myvalue"
  151. }
  152. successCases := []*secretsManagerTestCase{
  153. makeValidSecretsManagerTestCase(),
  154. makeValidSecretsManagerTestCaseCustom(setSecretString),
  155. makeValidSecretsManagerTestCaseCustom(setRemoteRefPropertyExistsInKey),
  156. makeValidSecretsManagerTestCaseCustom(setRemoteRefMissingProperty),
  157. makeValidSecretsManagerTestCaseCustom(setRemoteRefMissingPropertyInvalidJSON),
  158. makeValidSecretsManagerTestCaseCustom(setSecretBinaryNotSecretString),
  159. makeValidSecretsManagerTestCaseCustom(setSecretBinaryAndSecretStringToNil),
  160. makeValidSecretsManagerTestCaseCustom(setNestedSecretValueJSONParsing),
  161. makeValidSecretsManagerTestCaseCustom(setSecretValueWithDot),
  162. makeValidSecretsManagerTestCaseCustom(setCustomVersionStage),
  163. makeValidSecretsManagerTestCaseCustom(setCustomVersionID),
  164. makeValidSecretsManagerTestCaseCustom(setAPIErr),
  165. }
  166. for k, v := range successCases {
  167. sm := SecretsManager{
  168. cache: make(map[string]*awssm.GetSecretValueOutput),
  169. client: v.fakeClient,
  170. }
  171. out, err := sm.GetSecret(context.Background(), *v.remoteRef)
  172. if !ErrorContains(err, v.expectError) {
  173. t.Errorf(unexpectedErrorString, k, err.Error(), v.expectError)
  174. }
  175. if err == nil && string(out) != v.expectedSecret {
  176. t.Errorf("[%d] unexpected secret: expected %s, got %s", k, v.expectedSecret, string(out))
  177. }
  178. }
  179. }
  180. func TestCaching(t *testing.T) {
  181. fakeClient := fakesm.NewClient()
  182. // good case: first call, since we are using the same key, results should be cached and the counter should not go
  183. // over 1
  184. firstCall := func(smtc *secretsManagerTestCase) {
  185. smtc.apiOutput.SecretString = aws.String(`{"foo":"bar", "bar":"vodka"}`)
  186. smtc.remoteRef.Property = "foo"
  187. smtc.expectedSecret = "bar"
  188. smtc.expectedCounter = aws.Int(1)
  189. smtc.fakeClient = fakeClient
  190. }
  191. secondCall := func(smtc *secretsManagerTestCase) {
  192. smtc.apiOutput.SecretString = aws.String(`{"foo":"bar", "bar":"vodka"}`)
  193. smtc.remoteRef.Property = "bar"
  194. smtc.expectedSecret = "vodka"
  195. smtc.expectedCounter = aws.Int(1)
  196. smtc.fakeClient = fakeClient
  197. }
  198. notCachedCall := func(smtc *secretsManagerTestCase) {
  199. smtc.apiOutput.SecretString = aws.String(`{"sheldon":"bazinga", "bar":"foo"}`)
  200. smtc.remoteRef.Property = "sheldon"
  201. smtc.expectedSecret = "bazinga"
  202. smtc.expectedCounter = aws.Int(2)
  203. smtc.fakeClient = fakeClient
  204. smtc.apiInput.SecretId = aws.String("xyz")
  205. smtc.remoteRef.Key = "xyz" // it should reset the cache since the key is different
  206. }
  207. cachedCases := []*secretsManagerTestCase{
  208. makeValidSecretsManagerTestCaseCustom(firstCall),
  209. makeValidSecretsManagerTestCaseCustom(firstCall),
  210. makeValidSecretsManagerTestCaseCustom(secondCall),
  211. makeValidSecretsManagerTestCaseCustom(notCachedCall),
  212. }
  213. sm := SecretsManager{
  214. cache: make(map[string]*awssm.GetSecretValueOutput),
  215. }
  216. for k, v := range cachedCases {
  217. sm.client = v.fakeClient
  218. out, err := sm.GetSecret(context.Background(), *v.remoteRef)
  219. if !ErrorContains(err, v.expectError) {
  220. t.Errorf(unexpectedErrorString, k, err.Error(), v.expectError)
  221. }
  222. if err == nil && string(out) != v.expectedSecret {
  223. t.Errorf("[%d] unexpected secret: expected %s, got %s", k, v.expectedSecret, string(out))
  224. }
  225. if v.expectedCounter != nil && v.fakeClient.ExecutionCounter != *v.expectedCounter {
  226. t.Errorf("[%d] unexpected counter value: expected %d, got %d", k, v.expectedCounter, v.fakeClient.ExecutionCounter)
  227. }
  228. }
  229. }
  230. func TestGetSecretMap(t *testing.T) {
  231. // good case: default version & deserialization
  232. setDeserialization := func(smtc *secretsManagerTestCase) {
  233. smtc.apiOutput.SecretString = aws.String(`{"foo":"bar"}`)
  234. smtc.expectedData["foo"] = []byte("bar")
  235. }
  236. // good case: nested json
  237. setNestedJSON := func(smtc *secretsManagerTestCase) {
  238. smtc.apiOutput.SecretString = aws.String(`{"foobar":{"baz":"nestedval"}}`)
  239. smtc.expectedData["foobar"] = []byte("{\"baz\":\"nestedval\"}")
  240. }
  241. // good case: caching
  242. cachedMap := func(smtc *secretsManagerTestCase) {
  243. smtc.apiOutput.SecretString = aws.String(`{"foo":"bar", "plus": "one"}`)
  244. smtc.expectedData["foo"] = []byte("bar")
  245. smtc.expectedData["plus"] = []byte("one")
  246. smtc.expectedCounter = aws.Int(1)
  247. }
  248. // bad case: invalid json
  249. setInvalidJSON := func(smtc *secretsManagerTestCase) {
  250. smtc.apiOutput.SecretString = aws.String(`-----------------`)
  251. smtc.expectError = "unable to unmarshal secret"
  252. }
  253. successCases := []*secretsManagerTestCase{
  254. makeValidSecretsManagerTestCaseCustom(setDeserialization),
  255. makeValidSecretsManagerTestCaseCustom(setNestedJSON),
  256. makeValidSecretsManagerTestCaseCustom(setAPIErr),
  257. makeValidSecretsManagerTestCaseCustom(setInvalidJSON),
  258. makeValidSecretsManagerTestCaseCustom(cachedMap),
  259. }
  260. for k, v := range successCases {
  261. sm := SecretsManager{
  262. cache: make(map[string]*awssm.GetSecretValueOutput),
  263. client: v.fakeClient,
  264. }
  265. out, err := sm.GetSecretMap(context.Background(), *v.remoteRef)
  266. if !ErrorContains(err, v.expectError) {
  267. t.Errorf(unexpectedErrorString, k, err.Error(), v.expectError)
  268. }
  269. if err == nil && !cmp.Equal(out, v.expectedData) {
  270. t.Errorf("[%d] unexpected secret data: expected %#v, got %#v", k, v.expectedData, out)
  271. }
  272. if v.expectedCounter != nil && v.fakeClient.ExecutionCounter != *v.expectedCounter {
  273. t.Errorf("[%d] unexpected counter value: expected %d, got %d", k, v.expectedCounter, v.fakeClient.ExecutionCounter)
  274. }
  275. }
  276. }
  277. func ErrorContains(out error, want string) bool {
  278. if out == nil {
  279. return want == ""
  280. }
  281. if want == "" {
  282. return false
  283. }
  284. return strings.Contains(out.Error(), want)
  285. }