secretsmanager_test.go 13 KB

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