secretsmanager_test.go 24 KB

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