secretsmanager_test.go 11 KB

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