secretsmanager_test.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765
  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. "github.com/aws/aws-sdk-go/aws"
  20. "github.com/aws/aws-sdk-go/aws/awserr"
  21. awssm "github.com/aws/aws-sdk-go/service/secretsmanager"
  22. "github.com/google/go-cmp/cmp"
  23. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  24. esv1beta1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1beta1"
  25. fakesm "github.com/external-secrets/external-secrets/pkg/provider/aws/secretsmanager/fake"
  26. "github.com/external-secrets/external-secrets/pkg/provider/aws/util"
  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. const (
  43. tagname1 = "tagname1"
  44. tagvalue1 = "tagvalue1"
  45. tagname2 = "tagname2"
  46. tagvalue2 = "tagvalue2"
  47. )
  48. func makeValidSecretsManagerTestCase() *secretsManagerTestCase {
  49. smtc := secretsManagerTestCase{
  50. fakeClient: fakesm.NewClient(),
  51. apiInput: makeValidAPIInput(),
  52. remoteRef: makeValidRemoteRef(),
  53. apiOutput: makeValidAPIOutput(),
  54. apiErr: nil,
  55. expectError: "",
  56. expectedSecret: "",
  57. expectedData: map[string][]byte{},
  58. }
  59. smtc.fakeClient.WithValue(smtc.apiInput, smtc.apiOutput, smtc.apiErr)
  60. return &smtc
  61. }
  62. func makeValidRemoteRef() *esv1beta1.ExternalSecretDataRemoteRef {
  63. return &esv1beta1.ExternalSecretDataRemoteRef{
  64. Key: "/baz",
  65. Version: "AWSCURRENT",
  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: secretOut.SecretBinary no JSON parsing if name on key
  141. setSecretValueWithDot := func(smtc *secretsManagerTestCase) {
  142. smtc.apiOutput.SecretString = nil
  143. smtc.apiOutput.SecretBinary = []byte(`{"foobar.baz":"nestedval"}`)
  144. smtc.remoteRef.Property = "foobar.baz"
  145. smtc.expectedSecret = "nestedval"
  146. }
  147. // good case: custom version stage set
  148. setCustomVersionStage := func(smtc *secretsManagerTestCase) {
  149. smtc.apiInput.VersionStage = aws.String("1234")
  150. smtc.remoteRef.Version = "1234"
  151. smtc.apiOutput.SecretString = aws.String("FOOBA!")
  152. smtc.expectedSecret = "FOOBA!"
  153. }
  154. // good case: custom version id set
  155. setCustomVersionID := func(smtc *secretsManagerTestCase) {
  156. smtc.apiInput.VersionStage = nil
  157. smtc.apiInput.VersionId = aws.String("1234-5678")
  158. smtc.remoteRef.Version = "uuid/1234-5678"
  159. smtc.apiOutput.SecretString = aws.String("myvalue")
  160. smtc.expectedSecret = "myvalue"
  161. }
  162. fetchMetadata := func(smtc *secretsManagerTestCase) {
  163. smtc.remoteRef.MetadataPolicy = esv1beta1.ExternalSecretMetadataPolicyFetch
  164. describeSecretOutput := &awssm.DescribeSecretOutput{
  165. Tags: getTagSlice(),
  166. }
  167. smtc.fakeClient.DescribeSecretWithContextFn = fakesm.NewDescribeSecretWithContextFn(describeSecretOutput, nil)
  168. jsonTags, _ := util.SecretTagsToJSONString(getTagSlice())
  169. smtc.apiOutput.SecretString = &jsonTags
  170. smtc.expectedSecret = jsonTags
  171. }
  172. fetchMetadataProperty := func(smtc *secretsManagerTestCase) {
  173. smtc.remoteRef.MetadataPolicy = esv1beta1.ExternalSecretMetadataPolicyFetch
  174. describeSecretOutput := &awssm.DescribeSecretOutput{
  175. Tags: getTagSlice(),
  176. }
  177. smtc.fakeClient.DescribeSecretWithContextFn = fakesm.NewDescribeSecretWithContextFn(describeSecretOutput, nil)
  178. smtc.remoteRef.Property = tagname2
  179. jsonTags, _ := util.SecretTagsToJSONString(getTagSlice())
  180. smtc.apiOutput.SecretString = &jsonTags
  181. smtc.expectedSecret = tagvalue2
  182. }
  183. failMetadataWrongProperty := func(smtc *secretsManagerTestCase) {
  184. smtc.remoteRef.MetadataPolicy = esv1beta1.ExternalSecretMetadataPolicyFetch
  185. describeSecretOutput := &awssm.DescribeSecretOutput{
  186. Tags: getTagSlice(),
  187. }
  188. smtc.fakeClient.DescribeSecretWithContextFn = fakesm.NewDescribeSecretWithContextFn(describeSecretOutput, nil)
  189. smtc.remoteRef.Property = "fail"
  190. jsonTags, _ := util.SecretTagsToJSONString(getTagSlice())
  191. smtc.apiOutput.SecretString = &jsonTags
  192. smtc.expectError = "key fail does not exist in secret /baz"
  193. }
  194. successCases := []*secretsManagerTestCase{
  195. makeValidSecretsManagerTestCase(),
  196. makeValidSecretsManagerTestCaseCustom(setSecretString),
  197. makeValidSecretsManagerTestCaseCustom(setRemoteRefPropertyExistsInKey),
  198. makeValidSecretsManagerTestCaseCustom(setRemoteRefMissingProperty),
  199. makeValidSecretsManagerTestCaseCustom(setRemoteRefMissingPropertyInvalidJSON),
  200. makeValidSecretsManagerTestCaseCustom(setSecretBinaryNotSecretString),
  201. makeValidSecretsManagerTestCaseCustom(setSecretBinaryAndSecretStringToNil),
  202. makeValidSecretsManagerTestCaseCustom(setNestedSecretValueJSONParsing),
  203. makeValidSecretsManagerTestCaseCustom(setSecretValueWithDot),
  204. makeValidSecretsManagerTestCaseCustom(setCustomVersionStage),
  205. makeValidSecretsManagerTestCaseCustom(setCustomVersionID),
  206. makeValidSecretsManagerTestCaseCustom(setAPIErr),
  207. makeValidSecretsManagerTestCaseCustom(fetchMetadata),
  208. makeValidSecretsManagerTestCaseCustom(fetchMetadataProperty),
  209. makeValidSecretsManagerTestCaseCustom(failMetadataWrongProperty),
  210. }
  211. for k, v := range successCases {
  212. sm := SecretsManager{
  213. cache: make(map[string]*awssm.GetSecretValueOutput),
  214. client: v.fakeClient,
  215. }
  216. out, err := sm.GetSecret(context.Background(), *v.remoteRef)
  217. if !ErrorContains(err, v.expectError) {
  218. t.Errorf(unexpectedErrorString, k, err.Error(), v.expectError)
  219. }
  220. if err == nil && string(out) != v.expectedSecret {
  221. t.Errorf("[%d] unexpected secret: expected %s, got %s", k, v.expectedSecret, string(out))
  222. }
  223. }
  224. }
  225. func TestCaching(t *testing.T) {
  226. fakeClient := fakesm.NewClient()
  227. // good case: first call, since we are using the same key, results should be cached and the counter should not go
  228. // over 1
  229. firstCall := func(smtc *secretsManagerTestCase) {
  230. smtc.apiOutput.SecretString = aws.String(`{"foo":"bar", "bar":"vodka"}`)
  231. smtc.remoteRef.Property = "foo"
  232. smtc.expectedSecret = "bar"
  233. smtc.expectedCounter = aws.Int(1)
  234. smtc.fakeClient = fakeClient
  235. }
  236. secondCall := func(smtc *secretsManagerTestCase) {
  237. smtc.apiOutput.SecretString = aws.String(`{"foo":"bar", "bar":"vodka"}`)
  238. smtc.remoteRef.Property = "bar"
  239. smtc.expectedSecret = "vodka"
  240. smtc.expectedCounter = aws.Int(1)
  241. smtc.fakeClient = fakeClient
  242. }
  243. notCachedCall := func(smtc *secretsManagerTestCase) {
  244. smtc.apiOutput.SecretString = aws.String(`{"sheldon":"bazinga", "bar":"foo"}`)
  245. smtc.remoteRef.Property = "sheldon"
  246. smtc.expectedSecret = "bazinga"
  247. smtc.expectedCounter = aws.Int(2)
  248. smtc.fakeClient = fakeClient
  249. smtc.apiInput.SecretId = aws.String("xyz")
  250. smtc.remoteRef.Key = "xyz" // it should reset the cache since the key is different
  251. }
  252. cachedCases := []*secretsManagerTestCase{
  253. makeValidSecretsManagerTestCaseCustom(firstCall),
  254. makeValidSecretsManagerTestCaseCustom(firstCall),
  255. makeValidSecretsManagerTestCaseCustom(secondCall),
  256. makeValidSecretsManagerTestCaseCustom(notCachedCall),
  257. }
  258. sm := SecretsManager{
  259. cache: make(map[string]*awssm.GetSecretValueOutput),
  260. }
  261. for k, v := range cachedCases {
  262. sm.client = v.fakeClient
  263. out, err := sm.GetSecret(context.Background(), *v.remoteRef)
  264. if !ErrorContains(err, v.expectError) {
  265. t.Errorf(unexpectedErrorString, k, err.Error(), v.expectError)
  266. }
  267. if err == nil && string(out) != v.expectedSecret {
  268. t.Errorf("[%d] unexpected secret: expected %s, got %s", k, v.expectedSecret, string(out))
  269. }
  270. if v.expectedCounter != nil && v.fakeClient.ExecutionCounter != *v.expectedCounter {
  271. t.Errorf("[%d] unexpected counter value: expected %d, got %d", k, v.expectedCounter, v.fakeClient.ExecutionCounter)
  272. }
  273. }
  274. }
  275. func TestGetSecretMap(t *testing.T) {
  276. // good case: default version & deserialization
  277. setDeserialization := func(smtc *secretsManagerTestCase) {
  278. smtc.apiOutput.SecretString = aws.String(`{"foo":"bar"}`)
  279. smtc.expectedData["foo"] = []byte("bar")
  280. }
  281. // good case: nested json
  282. setNestedJSON := func(smtc *secretsManagerTestCase) {
  283. smtc.apiOutput.SecretString = aws.String(`{"foobar":{"baz":"nestedval"}}`)
  284. smtc.expectedData["foobar"] = []byte("{\"baz\":\"nestedval\"}")
  285. }
  286. // good case: caching
  287. cachedMap := func(smtc *secretsManagerTestCase) {
  288. smtc.apiOutput.SecretString = aws.String(`{"foo":"bar", "plus": "one"}`)
  289. smtc.expectedData["foo"] = []byte("bar")
  290. smtc.expectedData["plus"] = []byte("one")
  291. smtc.expectedCounter = aws.Int(1)
  292. }
  293. // bad case: invalid json
  294. setInvalidJSON := func(smtc *secretsManagerTestCase) {
  295. smtc.apiOutput.SecretString = aws.String(`-----------------`)
  296. smtc.expectError = "unable to unmarshal secret"
  297. }
  298. successCases := []*secretsManagerTestCase{
  299. makeValidSecretsManagerTestCaseCustom(setDeserialization),
  300. makeValidSecretsManagerTestCaseCustom(setNestedJSON),
  301. makeValidSecretsManagerTestCaseCustom(setAPIErr),
  302. makeValidSecretsManagerTestCaseCustom(setInvalidJSON),
  303. makeValidSecretsManagerTestCaseCustom(cachedMap),
  304. }
  305. for k, v := range successCases {
  306. sm := SecretsManager{
  307. cache: make(map[string]*awssm.GetSecretValueOutput),
  308. client: v.fakeClient,
  309. }
  310. out, err := sm.GetSecretMap(context.Background(), *v.remoteRef)
  311. if !ErrorContains(err, v.expectError) {
  312. t.Errorf(unexpectedErrorString, k, err.Error(), v.expectError)
  313. }
  314. if err == nil && !cmp.Equal(out, v.expectedData) {
  315. t.Errorf("[%d] unexpected secret data: expected %#v, got %#v", k, v.expectedData, out)
  316. }
  317. if v.expectedCounter != nil && v.fakeClient.ExecutionCounter != *v.expectedCounter {
  318. t.Errorf("[%d] unexpected counter value: expected %d, got %d", k, v.expectedCounter, v.fakeClient.ExecutionCounter)
  319. }
  320. }
  321. }
  322. func ErrorContains(out error, want string) bool {
  323. if out == nil {
  324. return want == ""
  325. }
  326. if want == "" {
  327. return false
  328. }
  329. return strings.Contains(out.Error(), want)
  330. }
  331. type fakeRef struct {
  332. key string
  333. }
  334. func (f fakeRef) GetRemoteKey() string {
  335. return f.key
  336. }
  337. func TestSetSecret(t *testing.T) {
  338. managedBy := managedBy
  339. notManagedBy := "not-managed-by"
  340. secretValue := []byte("fake-value")
  341. externalSecrets := externalSecrets
  342. noPermission := errors.New("no permission")
  343. arn := "arn:aws:secretsmanager:us-east-1:702902267788:secret:foo-bar5-Robbgh"
  344. getSecretCorrectErr := awssm.ResourceNotFoundException{}
  345. getSecretWrongErr := awssm.InvalidRequestException{}
  346. secretOutput := &awssm.CreateSecretOutput{
  347. ARN: &arn,
  348. }
  349. externalSecretsTag := []*awssm.Tag{
  350. {
  351. Key: &managedBy,
  352. Value: &externalSecrets,
  353. },
  354. }
  355. externalSecretsTagFaulty := []*awssm.Tag{
  356. {
  357. Key: &notManagedBy,
  358. Value: &externalSecrets,
  359. },
  360. }
  361. tagSecretOutput := &awssm.DescribeSecretOutput{
  362. ARN: &arn,
  363. Tags: externalSecretsTag,
  364. }
  365. tagSecretOutputFaulty := &awssm.DescribeSecretOutput{
  366. ARN: &arn,
  367. Tags: externalSecretsTagFaulty,
  368. }
  369. secretValueOutput := &awssm.GetSecretValueOutput{
  370. ARN: &arn,
  371. }
  372. secretValueOutput2 := &awssm.GetSecretValueOutput{
  373. ARN: &arn,
  374. SecretBinary: secretValue,
  375. }
  376. blankSecretValueOutput := &awssm.GetSecretValueOutput{}
  377. putSecretOutput := &awssm.PutSecretValueOutput{
  378. ARN: &arn,
  379. }
  380. type args struct {
  381. store *esv1beta1.AWSProvider
  382. client fakesm.Client
  383. }
  384. type want struct {
  385. err error
  386. }
  387. tests := map[string]struct {
  388. reason string
  389. args args
  390. want want
  391. }{
  392. "SetSecretSucceedsWithExistingSecret": {
  393. reason: "a secret can be pushed to aws secrets manager when it already exists",
  394. args: args{
  395. store: makeValidSecretStore().Spec.Provider.AWS,
  396. client: fakesm.Client{
  397. GetSecretValueWithContextFn: fakesm.NewGetSecretValueWithContextFn(secretValueOutput, nil),
  398. CreateSecretWithContextFn: fakesm.NewCreateSecretWithContextFn(secretOutput, nil),
  399. PutSecretValueWithContextFn: fakesm.NewPutSecretValueWithContextFn(putSecretOutput, nil),
  400. DescribeSecretWithContextFn: fakesm.NewDescribeSecretWithContextFn(tagSecretOutput, nil),
  401. },
  402. },
  403. want: want{
  404. err: nil,
  405. },
  406. },
  407. "SetSecretSucceedsWithNewSecret": {
  408. reason: "a secret can be pushed to aws secrets manager if it doesn't already exist",
  409. args: args{
  410. store: makeValidSecretStore().Spec.Provider.AWS,
  411. client: fakesm.Client{
  412. GetSecretValueWithContextFn: fakesm.NewGetSecretValueWithContextFn(blankSecretValueOutput, &getSecretCorrectErr),
  413. CreateSecretWithContextFn: fakesm.NewCreateSecretWithContextFn(secretOutput, nil),
  414. },
  415. },
  416. want: want{
  417. err: nil,
  418. },
  419. },
  420. "SetSecretCreateSecretFails": {
  421. reason: "CreateSecretWithContext returns an error if it fails",
  422. args: args{
  423. store: makeValidSecretStore().Spec.Provider.AWS,
  424. client: fakesm.Client{
  425. GetSecretValueWithContextFn: fakesm.NewGetSecretValueWithContextFn(blankSecretValueOutput, &getSecretCorrectErr),
  426. CreateSecretWithContextFn: fakesm.NewCreateSecretWithContextFn(nil, noPermission),
  427. },
  428. },
  429. want: want{
  430. err: noPermission,
  431. },
  432. },
  433. "SetSecretGetSecretFails": {
  434. reason: "GetSecretValueWithContext returns an error if it fails",
  435. args: args{
  436. store: makeValidSecretStore().Spec.Provider.AWS,
  437. client: fakesm.Client{
  438. GetSecretValueWithContextFn: fakesm.NewGetSecretValueWithContextFn(blankSecretValueOutput, noPermission),
  439. },
  440. },
  441. want: want{
  442. err: noPermission,
  443. },
  444. },
  445. "SetSecretWillNotPushSameSecret": {
  446. reason: "secret with the same value will not be pushed",
  447. args: args{
  448. store: makeValidSecretStore().Spec.Provider.AWS,
  449. client: fakesm.Client{
  450. GetSecretValueWithContextFn: fakesm.NewGetSecretValueWithContextFn(secretValueOutput2, nil),
  451. DescribeSecretWithContextFn: fakesm.NewDescribeSecretWithContextFn(tagSecretOutput, nil),
  452. },
  453. },
  454. want: want{
  455. err: nil,
  456. },
  457. },
  458. "SetSecretPutSecretValueFails": {
  459. reason: "PutSecretValueWithContext returns an error if it fails",
  460. args: args{
  461. store: makeValidSecretStore().Spec.Provider.AWS,
  462. client: fakesm.Client{
  463. GetSecretValueWithContextFn: fakesm.NewGetSecretValueWithContextFn(secretValueOutput, nil),
  464. PutSecretValueWithContextFn: fakesm.NewPutSecretValueWithContextFn(nil, noPermission),
  465. DescribeSecretWithContextFn: fakesm.NewDescribeSecretWithContextFn(tagSecretOutput, nil),
  466. },
  467. },
  468. want: want{
  469. err: noPermission,
  470. },
  471. },
  472. "SetSecretWrongGetSecretErrFails": {
  473. reason: "GetSecretValueWithContext errors out when anything except awssm.ErrCodeResourceNotFoundException",
  474. args: args{
  475. store: makeValidSecretStore().Spec.Provider.AWS,
  476. client: fakesm.Client{
  477. GetSecretValueWithContextFn: fakesm.NewGetSecretValueWithContextFn(blankSecretValueOutput, &getSecretWrongErr),
  478. },
  479. },
  480. want: want{
  481. err: &getSecretWrongErr,
  482. },
  483. },
  484. "SetSecretDescribeSecretFails": {
  485. reason: "secret cannot be described",
  486. args: args{
  487. store: makeValidSecretStore().Spec.Provider.AWS,
  488. client: fakesm.Client{
  489. GetSecretValueWithContextFn: fakesm.NewGetSecretValueWithContextFn(secretValueOutput, nil),
  490. DescribeSecretWithContextFn: fakesm.NewDescribeSecretWithContextFn(nil, noPermission),
  491. },
  492. },
  493. want: want{
  494. err: noPermission,
  495. },
  496. },
  497. "SetSecretDoesNotOverwriteUntaggedSecret": {
  498. reason: "secret cannot be described",
  499. args: args{
  500. store: makeValidSecretStore().Spec.Provider.AWS,
  501. client: fakesm.Client{
  502. GetSecretValueWithContextFn: fakesm.NewGetSecretValueWithContextFn(secretValueOutput, nil),
  503. DescribeSecretWithContextFn: fakesm.NewDescribeSecretWithContextFn(tagSecretOutputFaulty, nil),
  504. },
  505. },
  506. want: want{
  507. err: fmt.Errorf("secret not managed by external-secrets"),
  508. },
  509. },
  510. }
  511. for name, tc := range tests {
  512. t.Run(name, func(t *testing.T) {
  513. ref := fakeRef{key: "fake-key"}
  514. sm := SecretsManager{
  515. client: &tc.args.client,
  516. }
  517. err := sm.PushSecret(context.Background(), []byte("fake-value"), ref)
  518. // Error nil XOR tc.want.err nil
  519. if ((err == nil) || (tc.want.err == nil)) && !((err == nil) && (tc.want.err == nil)) {
  520. t.Errorf("\nTesting SetSecret:\nName: %v\nReason: %v\nWant error: %v\nGot error: %v", name, tc.reason, tc.want.err, err)
  521. }
  522. // if errors are the same type but their contents do not match
  523. if err != nil && tc.want.err != nil {
  524. if !strings.Contains(err.Error(), tc.want.err.Error()) {
  525. t.Errorf("\nTesting SetSecret:\nName: %v\nReason: %v\nWant error: %v\nGot error got nil", name, tc.reason, tc.want.err)
  526. }
  527. }
  528. })
  529. }
  530. }
  531. func TestDeleteSecret(t *testing.T) {
  532. fakeClient := fakesm.Client{}
  533. managed := managedBy
  534. manager := externalSecrets
  535. secretTag := awssm.Tag{
  536. Key: &managed,
  537. Value: &manager,
  538. }
  539. type args struct {
  540. client fakesm.Client
  541. getSecretOutput *awssm.GetSecretValueOutput
  542. describeSecretOutput *awssm.DescribeSecretOutput
  543. deleteSecretOutput *awssm.DeleteSecretOutput
  544. getSecretErr error
  545. describeSecretErr error
  546. deleteSecretErr error
  547. }
  548. type want struct {
  549. err error
  550. }
  551. type testCase struct {
  552. args args
  553. want want
  554. reason string
  555. }
  556. tests := map[string]testCase{
  557. "Deletes Successfully": {
  558. args: args{
  559. client: fakeClient,
  560. getSecretOutput: &awssm.GetSecretValueOutput{},
  561. describeSecretOutput: &awssm.DescribeSecretOutput{
  562. Tags: []*awssm.Tag{&secretTag},
  563. },
  564. deleteSecretOutput: &awssm.DeleteSecretOutput{},
  565. getSecretErr: nil,
  566. describeSecretErr: nil,
  567. deleteSecretErr: nil,
  568. },
  569. want: want{
  570. err: nil,
  571. },
  572. reason: "",
  573. },
  574. "Not Managed by ESO": {
  575. args: args{
  576. client: fakeClient,
  577. getSecretOutput: &awssm.GetSecretValueOutput{},
  578. describeSecretOutput: &awssm.DescribeSecretOutput{
  579. Tags: []*awssm.Tag{},
  580. },
  581. deleteSecretOutput: &awssm.DeleteSecretOutput{},
  582. getSecretErr: nil,
  583. describeSecretErr: nil,
  584. deleteSecretErr: nil,
  585. },
  586. want: want{
  587. err: nil,
  588. },
  589. reason: "",
  590. },
  591. "Failed to get Tags": {
  592. args: args{
  593. client: fakeClient,
  594. getSecretOutput: &awssm.GetSecretValueOutput{},
  595. describeSecretOutput: nil,
  596. deleteSecretOutput: nil,
  597. getSecretErr: nil,
  598. describeSecretErr: errors.New("failed to get tags"),
  599. deleteSecretErr: nil,
  600. },
  601. want: want{
  602. err: errors.New("failed to get tags"),
  603. },
  604. reason: "",
  605. },
  606. "Secret Not Found": {
  607. args: args{
  608. client: fakeClient,
  609. getSecretOutput: nil,
  610. describeSecretOutput: nil,
  611. deleteSecretOutput: nil,
  612. getSecretErr: awserr.New(awssm.ErrCodeResourceNotFoundException, "not here, sorry dude", nil),
  613. describeSecretErr: nil,
  614. deleteSecretErr: nil,
  615. },
  616. want: want{
  617. err: nil,
  618. },
  619. },
  620. "Not expected AWS error": {
  621. args: args{
  622. client: fakeClient,
  623. getSecretOutput: nil,
  624. describeSecretOutput: nil,
  625. deleteSecretOutput: nil,
  626. getSecretErr: awserr.New(awssm.ErrCodeEncryptionFailure, "aws unavailable", nil),
  627. describeSecretErr: nil,
  628. deleteSecretErr: nil,
  629. },
  630. want: want{
  631. err: errors.New("aws unavailable"),
  632. },
  633. },
  634. "unexpected error": {
  635. args: args{
  636. client: fakeClient,
  637. getSecretOutput: nil,
  638. describeSecretOutput: nil,
  639. deleteSecretOutput: nil,
  640. getSecretErr: errors.New("timeout"),
  641. describeSecretErr: nil,
  642. deleteSecretErr: nil,
  643. },
  644. want: want{
  645. err: errors.New("timeout"),
  646. },
  647. },
  648. }
  649. for name, tc := range tests {
  650. t.Run(name, func(t *testing.T) {
  651. ref := fakeRef{key: "fake-key"}
  652. sm := SecretsManager{
  653. client: &tc.args.client,
  654. }
  655. tc.args.client.GetSecretValueWithContextFn = fakesm.NewGetSecretValueWithContextFn(tc.args.getSecretOutput, tc.args.getSecretErr)
  656. tc.args.client.DescribeSecretWithContextFn = fakesm.NewDescribeSecretWithContextFn(tc.args.describeSecretOutput, tc.args.describeSecretErr)
  657. tc.args.client.DeleteSecretWithContextFn = fakesm.NewDeleteSecretWithContextFn(tc.args.deleteSecretOutput, tc.args.deleteSecretErr)
  658. err := sm.DeleteSecret(context.TODO(), ref)
  659. // Error nil XOR tc.want.err nil
  660. if ((err == nil) || (tc.want.err == nil)) && !((err == nil) && (tc.want.err == nil)) {
  661. t.Errorf("\nTesting SetSecret:\nName: %v\nReason: %v\nWant error: %v\nGot error: %v", name, tc.reason, tc.want.err, err)
  662. }
  663. // if errors are the same type but their contents do not match
  664. if err != nil && tc.want.err != nil {
  665. if !strings.Contains(err.Error(), tc.want.err.Error()) {
  666. t.Errorf("\nTesting SetSecret:\nName: %v\nReason: %v\nWant error: %v\nGot error got nil", name, tc.reason, tc.want.err)
  667. }
  668. }
  669. })
  670. }
  671. }
  672. func makeValidSecretStore() *esv1beta1.SecretStore {
  673. return &esv1beta1.SecretStore{
  674. ObjectMeta: metav1.ObjectMeta{
  675. Name: "aws-secret-store",
  676. Namespace: "default",
  677. },
  678. Spec: esv1beta1.SecretStoreSpec{
  679. Provider: &esv1beta1.SecretStoreProvider{
  680. AWS: &esv1beta1.AWSProvider{
  681. Service: esv1beta1.AWSServiceSecretsManager,
  682. Region: "eu-west-2",
  683. },
  684. },
  685. },
  686. }
  687. }
  688. func getTagSlice() []*awssm.Tag {
  689. tagKey1 := tagname1
  690. tagValue1 := tagvalue1
  691. tagKey2 := tagname2
  692. tagValue2 := tagvalue2
  693. return []*awssm.Tag{
  694. {
  695. Key: &tagKey1,
  696. Value: &tagValue1,
  697. },
  698. {
  699. Key: &tagKey2,
  700. Value: &tagValue2,
  701. },
  702. }
  703. }