secretsmanager_test.go 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956
  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. property string
  334. }
  335. func (f fakeRef) GetRemoteKey() string {
  336. return f.key
  337. }
  338. func (f fakeRef) GetProperty() string {
  339. return f.property
  340. }
  341. func TestSetSecret(t *testing.T) {
  342. managedBy := managedBy
  343. notManagedBy := "not-managed-by"
  344. secretValue := []byte("fake-value")
  345. externalSecrets := externalSecrets
  346. noPermission := errors.New("no permission")
  347. arn := "arn:aws:secretsmanager:us-east-1:702902267788:secret:foo-bar5-Robbgh"
  348. getSecretCorrectErr := awssm.ResourceNotFoundException{}
  349. getSecretWrongErr := awssm.InvalidRequestException{}
  350. secretOutput := &awssm.CreateSecretOutput{
  351. ARN: &arn,
  352. }
  353. externalSecretsTag := []*awssm.Tag{
  354. {
  355. Key: &managedBy,
  356. Value: &externalSecrets,
  357. },
  358. }
  359. externalSecretsTagFaulty := []*awssm.Tag{
  360. {
  361. Key: &notManagedBy,
  362. Value: &externalSecrets,
  363. },
  364. }
  365. tagSecretOutput := &awssm.DescribeSecretOutput{
  366. ARN: &arn,
  367. Tags: externalSecretsTag,
  368. }
  369. tagSecretOutputFaulty := &awssm.DescribeSecretOutput{
  370. ARN: &arn,
  371. Tags: externalSecretsTagFaulty,
  372. }
  373. initialVersion := "00000000-0000-0000-0000-000000000001"
  374. defaultVersion := "00000000-0000-0000-0000-000000000002"
  375. defaultUpdatedVersion := "00000000-0000-0000-0000-000000000003"
  376. randomUUIDVersion := "c2812e8d-84ce-4858-abec-7163d8ab312b"
  377. randomUUIDVersionIncremented := "c2812e8d-84ce-4858-abec-7163d8ab312c"
  378. unparsableVersion := "IAM UNPARSABLE"
  379. secretValueOutput := &awssm.GetSecretValueOutput{
  380. ARN: &arn,
  381. VersionId: &defaultVersion,
  382. }
  383. secretValueOutput2 := &awssm.GetSecretValueOutput{
  384. ARN: &arn,
  385. SecretBinary: secretValue,
  386. VersionId: &defaultVersion,
  387. }
  388. type params struct {
  389. s string
  390. b []byte
  391. version *string
  392. }
  393. secretValueOutputFrom := func(params params) *awssm.GetSecretValueOutput {
  394. var version *string
  395. if params.version == nil {
  396. version = &defaultVersion
  397. } else {
  398. version = params.version
  399. }
  400. return &awssm.GetSecretValueOutput{
  401. ARN: &arn,
  402. SecretString: &params.s,
  403. SecretBinary: params.b,
  404. VersionId: version,
  405. }
  406. }
  407. blankSecretValueOutput := &awssm.GetSecretValueOutput{}
  408. putSecretOutput := &awssm.PutSecretValueOutput{
  409. ARN: &arn,
  410. }
  411. remoteRefWithoutProperty := fakeRef{key: "fake-key", property: ""}
  412. remoteRefWithProperty := fakeRef{key: "fake-key", property: "other-fake-property"}
  413. type args struct {
  414. store *esv1beta1.AWSProvider
  415. client fakesm.Client
  416. remoteRef fakeRef
  417. }
  418. type want struct {
  419. err error
  420. }
  421. tests := map[string]struct {
  422. reason string
  423. args args
  424. want want
  425. }{
  426. "SetSecretSucceedsWithExistingSecret": {
  427. reason: "a secret can be pushed to aws secrets manager when it already exists",
  428. args: args{
  429. store: makeValidSecretStore().Spec.Provider.AWS,
  430. client: fakesm.Client{
  431. GetSecretValueWithContextFn: fakesm.NewGetSecretValueWithContextFn(secretValueOutput, nil),
  432. CreateSecretWithContextFn: fakesm.NewCreateSecretWithContextFn(secretOutput, nil),
  433. PutSecretValueWithContextFn: fakesm.NewPutSecretValueWithContextFn(putSecretOutput, nil),
  434. DescribeSecretWithContextFn: fakesm.NewDescribeSecretWithContextFn(tagSecretOutput, nil),
  435. },
  436. remoteRef: remoteRefWithoutProperty,
  437. },
  438. want: want{
  439. err: nil,
  440. },
  441. },
  442. "SetSecretSucceedsWithNewSecret": {
  443. reason: "a secret can be pushed to aws secrets manager if it doesn't already exist",
  444. args: args{
  445. store: makeValidSecretStore().Spec.Provider.AWS,
  446. client: fakesm.Client{
  447. GetSecretValueWithContextFn: fakesm.NewGetSecretValueWithContextFn(blankSecretValueOutput, &getSecretCorrectErr),
  448. CreateSecretWithContextFn: fakesm.NewCreateSecretWithContextFn(secretOutput, nil),
  449. },
  450. remoteRef: remoteRefWithoutProperty,
  451. },
  452. want: want{
  453. err: nil,
  454. },
  455. },
  456. "SetSecretWithPropertySucceedsWithNewSecret": {
  457. reason: "if a new secret is pushed to aws sm and a remoteRef property is specified, create a json secret with the remoteRef property as a key",
  458. args: args{
  459. store: makeValidSecretStore().Spec.Provider.AWS,
  460. client: fakesm.Client{
  461. GetSecretValueWithContextFn: fakesm.NewGetSecretValueWithContextFn(blankSecretValueOutput, &getSecretCorrectErr),
  462. CreateSecretWithContextFn: fakesm.NewCreateSecretWithContextFn(secretOutput, nil, []byte(`{"other-fake-property":"fake-value"}`)),
  463. },
  464. remoteRef: remoteRefWithProperty,
  465. },
  466. want: want{
  467. err: nil,
  468. },
  469. },
  470. "SetSecretWithPropertySucceedsWithExistingSecretAndNewPropertyBinary": {
  471. reason: "when a remoteRef property is specified, this property will be added to the sm secret if it is currently absent (sm secret is binary)",
  472. args: args{
  473. store: makeValidSecretStore().Spec.Provider.AWS,
  474. client: fakesm.Client{
  475. GetSecretValueWithContextFn: fakesm.NewGetSecretValueWithContextFn(secretValueOutputFrom(params{b: []byte((`{"fake-property":"fake-value"}`))}), nil),
  476. DescribeSecretWithContextFn: fakesm.NewDescribeSecretWithContextFn(tagSecretOutput, nil),
  477. PutSecretValueWithContextFn: fakesm.NewPutSecretValueWithContextFn(putSecretOutput, nil, fakesm.ExpectedPutSecretValueInput{
  478. SecretBinary: []byte(`{"fake-property":"fake-value","other-fake-property":"fake-value"}`),
  479. Version: &defaultUpdatedVersion,
  480. }),
  481. },
  482. remoteRef: remoteRefWithProperty,
  483. },
  484. want: want{
  485. err: nil,
  486. },
  487. },
  488. "SetSecretWithPropertySucceedsWithExistingSecretAndRandomUUIDVersion": {
  489. reason: "When a secret version is not specified, the client sets a random uuid by default. We should treat a version that can't be parsed to an int as not having a version",
  490. args: args{
  491. store: makeValidSecretStore().Spec.Provider.AWS,
  492. client: fakesm.Client{
  493. GetSecretValueWithContextFn: fakesm.NewGetSecretValueWithContextFn(secretValueOutputFrom(params{
  494. b: []byte((`{"fake-property":"fake-value"}`)),
  495. version: &randomUUIDVersion,
  496. }), nil),
  497. DescribeSecretWithContextFn: fakesm.NewDescribeSecretWithContextFn(tagSecretOutput, nil),
  498. PutSecretValueWithContextFn: fakesm.NewPutSecretValueWithContextFn(putSecretOutput, nil, fakesm.ExpectedPutSecretValueInput{
  499. SecretBinary: []byte(`{"fake-property":"fake-value","other-fake-property":"fake-value"}`),
  500. Version: &randomUUIDVersionIncremented,
  501. }),
  502. },
  503. remoteRef: remoteRefWithProperty,
  504. },
  505. want: want{
  506. err: nil,
  507. },
  508. },
  509. "SetSecretWithPropertySucceedsWithExistingSecretAndVersionThatCantBeParsed": {
  510. reason: "A manually set secret version doesn't have to be a UUID, we only support UUID secret versions though",
  511. args: args{
  512. store: makeValidSecretStore().Spec.Provider.AWS,
  513. client: fakesm.Client{
  514. GetSecretValueWithContextFn: fakesm.NewGetSecretValueWithContextFn(secretValueOutputFrom(params{
  515. b: []byte((`{"fake-property":"fake-value"}`)),
  516. version: &unparsableVersion,
  517. }), nil),
  518. DescribeSecretWithContextFn: fakesm.NewDescribeSecretWithContextFn(tagSecretOutput, nil),
  519. PutSecretValueWithContextFn: fakesm.NewPutSecretValueWithContextFn(putSecretOutput, nil, fakesm.ExpectedPutSecretValueInput{
  520. SecretBinary: []byte(`{"fake-property":"fake-value","other-fake-property":"fake-value"}`),
  521. Version: &initialVersion,
  522. }),
  523. },
  524. remoteRef: remoteRefWithProperty,
  525. },
  526. want: want{
  527. err: fmt.Errorf("expected secret version in AWS SSM to be a UUID but got '%s'", unparsableVersion),
  528. },
  529. },
  530. "SetSecretWithPropertySucceedsWithExistingSecretAndAbsentVersion": {
  531. reason: "When a secret version is not specified, set it to 1",
  532. args: args{
  533. store: makeValidSecretStore().Spec.Provider.AWS,
  534. client: fakesm.Client{
  535. GetSecretValueWithContextFn: fakesm.NewGetSecretValueWithContextFn(&awssm.GetSecretValueOutput{
  536. ARN: &arn,
  537. SecretBinary: []byte((`{"fake-property":"fake-value"}`)),
  538. }, nil),
  539. DescribeSecretWithContextFn: fakesm.NewDescribeSecretWithContextFn(tagSecretOutput, nil),
  540. PutSecretValueWithContextFn: fakesm.NewPutSecretValueWithContextFn(putSecretOutput, nil, fakesm.ExpectedPutSecretValueInput{
  541. SecretBinary: []byte(`{"fake-property":"fake-value","other-fake-property":"fake-value"}`),
  542. Version: &initialVersion,
  543. }),
  544. },
  545. remoteRef: remoteRefWithProperty,
  546. },
  547. want: want{
  548. err: nil,
  549. },
  550. },
  551. "SetSecretWithPropertySucceedsWithExistingSecretAndNewPropertyString": {
  552. reason: "when a remoteRef property is specified, this property will be added to the sm secret if it is currently absent (sm secret is a string)",
  553. args: args{
  554. store: makeValidSecretStore().Spec.Provider.AWS,
  555. client: fakesm.Client{
  556. GetSecretValueWithContextFn: fakesm.NewGetSecretValueWithContextFn(secretValueOutputFrom(params{s: `{"fake-property":"fake-value"}`}), nil),
  557. DescribeSecretWithContextFn: fakesm.NewDescribeSecretWithContextFn(tagSecretOutput, nil),
  558. PutSecretValueWithContextFn: fakesm.NewPutSecretValueWithContextFn(putSecretOutput, nil, fakesm.ExpectedPutSecretValueInput{
  559. SecretBinary: []byte(`{"fake-property":"fake-value","other-fake-property":"fake-value"}`),
  560. Version: &defaultUpdatedVersion,
  561. }),
  562. },
  563. remoteRef: remoteRefWithProperty,
  564. },
  565. want: want{
  566. err: nil,
  567. },
  568. },
  569. "SetSecretWithPropertySucceedsWithExistingSecretAndNewPropertyWithDot": {
  570. reason: "when a remoteRef property is specified, this property will be added to the sm secret if it is currently absent (remoteRef property is a sub-object)",
  571. args: args{
  572. store: makeValidSecretStore().Spec.Provider.AWS,
  573. client: fakesm.Client{
  574. GetSecretValueWithContextFn: fakesm.NewGetSecretValueWithContextFn(secretValueOutputFrom(params{s: `{"fake-property":{"fake-property":"fake-value"}}`}), nil),
  575. DescribeSecretWithContextFn: fakesm.NewDescribeSecretWithContextFn(tagSecretOutput, nil),
  576. PutSecretValueWithContextFn: fakesm.NewPutSecretValueWithContextFn(putSecretOutput, nil, fakesm.ExpectedPutSecretValueInput{
  577. SecretBinary: []byte(`{"fake-property":{"fake-property":"fake-value","other-fake-property":"fake-value"}}`),
  578. Version: &defaultUpdatedVersion,
  579. }),
  580. },
  581. remoteRef: fakeRef{key: "fake-key", property: "fake-property.other-fake-property"},
  582. },
  583. want: want{
  584. err: nil,
  585. },
  586. },
  587. "SetSecretWithPropertyFailsExistingNonJsonSecret": {
  588. reason: "setting a remoteRef property is only supported for json secrets",
  589. args: args{
  590. store: makeValidSecretStore().Spec.Provider.AWS,
  591. client: fakesm.Client{
  592. GetSecretValueWithContextFn: fakesm.NewGetSecretValueWithContextFn(secretValueOutputFrom(params{s: `non-json-secret`}), nil),
  593. DescribeSecretWithContextFn: fakesm.NewDescribeSecretWithContextFn(tagSecretOutput, nil),
  594. },
  595. remoteRef: remoteRefWithProperty,
  596. },
  597. want: want{
  598. err: errors.New("PushSecret for aws secrets manager with a remoteRef property requires a json secret"),
  599. },
  600. },
  601. "SetSecretCreateSecretFails": {
  602. reason: "CreateSecretWithContext returns an error if it fails",
  603. args: args{
  604. store: makeValidSecretStore().Spec.Provider.AWS,
  605. client: fakesm.Client{
  606. GetSecretValueWithContextFn: fakesm.NewGetSecretValueWithContextFn(blankSecretValueOutput, &getSecretCorrectErr),
  607. CreateSecretWithContextFn: fakesm.NewCreateSecretWithContextFn(nil, noPermission),
  608. },
  609. remoteRef: remoteRefWithoutProperty,
  610. },
  611. want: want{
  612. err: noPermission,
  613. },
  614. },
  615. "SetSecretGetSecretFails": {
  616. reason: "GetSecretValueWithContext returns an error if it fails",
  617. args: args{
  618. store: makeValidSecretStore().Spec.Provider.AWS,
  619. client: fakesm.Client{
  620. GetSecretValueWithContextFn: fakesm.NewGetSecretValueWithContextFn(blankSecretValueOutput, noPermission),
  621. },
  622. remoteRef: remoteRefWithoutProperty,
  623. },
  624. want: want{
  625. err: noPermission,
  626. },
  627. },
  628. "SetSecretWillNotPushSameSecret": {
  629. reason: "secret with the same value will not be pushed",
  630. args: args{
  631. store: makeValidSecretStore().Spec.Provider.AWS,
  632. client: fakesm.Client{
  633. GetSecretValueWithContextFn: fakesm.NewGetSecretValueWithContextFn(secretValueOutput2, nil),
  634. DescribeSecretWithContextFn: fakesm.NewDescribeSecretWithContextFn(tagSecretOutput, nil),
  635. },
  636. remoteRef: remoteRefWithoutProperty,
  637. },
  638. want: want{
  639. err: nil,
  640. },
  641. },
  642. "SetSecretPutSecretValueFails": {
  643. reason: "PutSecretValueWithContext returns an error if it fails",
  644. args: args{
  645. store: makeValidSecretStore().Spec.Provider.AWS,
  646. client: fakesm.Client{
  647. GetSecretValueWithContextFn: fakesm.NewGetSecretValueWithContextFn(secretValueOutput, nil),
  648. PutSecretValueWithContextFn: fakesm.NewPutSecretValueWithContextFn(nil, noPermission),
  649. DescribeSecretWithContextFn: fakesm.NewDescribeSecretWithContextFn(tagSecretOutput, nil),
  650. },
  651. remoteRef: remoteRefWithoutProperty,
  652. },
  653. want: want{
  654. err: noPermission,
  655. },
  656. },
  657. "SetSecretWrongGetSecretErrFails": {
  658. reason: "GetSecretValueWithContext errors out when anything except awssm.ErrCodeResourceNotFoundException",
  659. args: args{
  660. store: makeValidSecretStore().Spec.Provider.AWS,
  661. client: fakesm.Client{
  662. GetSecretValueWithContextFn: fakesm.NewGetSecretValueWithContextFn(blankSecretValueOutput, &getSecretWrongErr),
  663. },
  664. remoteRef: remoteRefWithoutProperty,
  665. },
  666. want: want{
  667. err: &getSecretWrongErr,
  668. },
  669. },
  670. "SetSecretDescribeSecretFails": {
  671. reason: "secret cannot be described",
  672. args: args{
  673. store: makeValidSecretStore().Spec.Provider.AWS,
  674. client: fakesm.Client{
  675. GetSecretValueWithContextFn: fakesm.NewGetSecretValueWithContextFn(secretValueOutput, nil),
  676. DescribeSecretWithContextFn: fakesm.NewDescribeSecretWithContextFn(nil, noPermission),
  677. },
  678. remoteRef: remoteRefWithoutProperty,
  679. },
  680. want: want{
  681. err: noPermission,
  682. },
  683. },
  684. "SetSecretDoesNotOverwriteUntaggedSecret": {
  685. reason: "secret cannot be described",
  686. args: args{
  687. store: makeValidSecretStore().Spec.Provider.AWS,
  688. client: fakesm.Client{
  689. GetSecretValueWithContextFn: fakesm.NewGetSecretValueWithContextFn(secretValueOutput, nil),
  690. DescribeSecretWithContextFn: fakesm.NewDescribeSecretWithContextFn(tagSecretOutputFaulty, nil),
  691. },
  692. remoteRef: remoteRefWithoutProperty,
  693. },
  694. want: want{
  695. err: fmt.Errorf("secret not managed by external-secrets"),
  696. },
  697. },
  698. }
  699. for name, tc := range tests {
  700. t.Run(name, func(t *testing.T) {
  701. sm := SecretsManager{
  702. client: &tc.args.client,
  703. }
  704. err := sm.PushSecret(context.Background(), []byte("fake-value"), nil, tc.args.remoteRef)
  705. // Error nil XOR tc.want.err nil
  706. if ((err == nil) || (tc.want.err == nil)) && !((err == nil) && (tc.want.err == nil)) {
  707. t.Errorf("\nTesting SetSecret:\nName: %v\nReason: %v\nWant error: %v\nGot error: %v", name, tc.reason, tc.want.err, err)
  708. }
  709. // if errors are the same type but their contents do not match
  710. if err != nil && tc.want.err != nil {
  711. if !strings.Contains(err.Error(), tc.want.err.Error()) {
  712. t.Errorf("\nTesting SetSecret:\nName: %v\nReason: %v\nWant error: %v\nGot error got nil", name, tc.reason, tc.want.err)
  713. }
  714. }
  715. })
  716. }
  717. }
  718. func TestDeleteSecret(t *testing.T) {
  719. fakeClient := fakesm.Client{}
  720. managed := managedBy
  721. manager := externalSecrets
  722. secretTag := awssm.Tag{
  723. Key: &managed,
  724. Value: &manager,
  725. }
  726. type args struct {
  727. client fakesm.Client
  728. getSecretOutput *awssm.GetSecretValueOutput
  729. describeSecretOutput *awssm.DescribeSecretOutput
  730. deleteSecretOutput *awssm.DeleteSecretOutput
  731. getSecretErr error
  732. describeSecretErr error
  733. deleteSecretErr error
  734. }
  735. type want struct {
  736. err error
  737. }
  738. type testCase struct {
  739. args args
  740. want want
  741. reason string
  742. }
  743. tests := map[string]testCase{
  744. "Deletes Successfully": {
  745. args: args{
  746. client: fakeClient,
  747. getSecretOutput: &awssm.GetSecretValueOutput{},
  748. describeSecretOutput: &awssm.DescribeSecretOutput{
  749. Tags: []*awssm.Tag{&secretTag},
  750. },
  751. deleteSecretOutput: &awssm.DeleteSecretOutput{},
  752. getSecretErr: nil,
  753. describeSecretErr: nil,
  754. deleteSecretErr: nil,
  755. },
  756. want: want{
  757. err: nil,
  758. },
  759. reason: "",
  760. },
  761. "Not Managed by ESO": {
  762. args: args{
  763. client: fakeClient,
  764. getSecretOutput: &awssm.GetSecretValueOutput{},
  765. describeSecretOutput: &awssm.DescribeSecretOutput{
  766. Tags: []*awssm.Tag{},
  767. },
  768. deleteSecretOutput: &awssm.DeleteSecretOutput{},
  769. getSecretErr: nil,
  770. describeSecretErr: nil,
  771. deleteSecretErr: nil,
  772. },
  773. want: want{
  774. err: nil,
  775. },
  776. reason: "",
  777. },
  778. "Failed to get Tags": {
  779. args: args{
  780. client: fakeClient,
  781. getSecretOutput: &awssm.GetSecretValueOutput{},
  782. describeSecretOutput: nil,
  783. deleteSecretOutput: nil,
  784. getSecretErr: nil,
  785. describeSecretErr: errors.New("failed to get tags"),
  786. deleteSecretErr: nil,
  787. },
  788. want: want{
  789. err: errors.New("failed to get tags"),
  790. },
  791. reason: "",
  792. },
  793. "Secret Not Found": {
  794. args: args{
  795. client: fakeClient,
  796. getSecretOutput: nil,
  797. describeSecretOutput: nil,
  798. deleteSecretOutput: nil,
  799. getSecretErr: awserr.New(awssm.ErrCodeResourceNotFoundException, "not here, sorry dude", nil),
  800. describeSecretErr: nil,
  801. deleteSecretErr: nil,
  802. },
  803. want: want{
  804. err: nil,
  805. },
  806. },
  807. "Not expected AWS error": {
  808. args: args{
  809. client: fakeClient,
  810. getSecretOutput: nil,
  811. describeSecretOutput: nil,
  812. deleteSecretOutput: nil,
  813. getSecretErr: awserr.New(awssm.ErrCodeEncryptionFailure, "aws unavailable", nil),
  814. describeSecretErr: nil,
  815. deleteSecretErr: nil,
  816. },
  817. want: want{
  818. err: errors.New("aws unavailable"),
  819. },
  820. },
  821. "unexpected error": {
  822. args: args{
  823. client: fakeClient,
  824. getSecretOutput: nil,
  825. describeSecretOutput: nil,
  826. deleteSecretOutput: nil,
  827. getSecretErr: errors.New("timeout"),
  828. describeSecretErr: nil,
  829. deleteSecretErr: nil,
  830. },
  831. want: want{
  832. err: errors.New("timeout"),
  833. },
  834. },
  835. }
  836. for name, tc := range tests {
  837. t.Run(name, func(t *testing.T) {
  838. ref := fakeRef{key: "fake-key"}
  839. sm := SecretsManager{
  840. client: &tc.args.client,
  841. }
  842. tc.args.client.GetSecretValueWithContextFn = fakesm.NewGetSecretValueWithContextFn(tc.args.getSecretOutput, tc.args.getSecretErr)
  843. tc.args.client.DescribeSecretWithContextFn = fakesm.NewDescribeSecretWithContextFn(tc.args.describeSecretOutput, tc.args.describeSecretErr)
  844. tc.args.client.DeleteSecretWithContextFn = fakesm.NewDeleteSecretWithContextFn(tc.args.deleteSecretOutput, tc.args.deleteSecretErr)
  845. err := sm.DeleteSecret(context.TODO(), ref)
  846. // Error nil XOR tc.want.err nil
  847. if ((err == nil) || (tc.want.err == nil)) && !((err == nil) && (tc.want.err == nil)) {
  848. t.Errorf("\nTesting SetSecret:\nName: %v\nReason: %v\nWant error: %v\nGot error: %v", name, tc.reason, tc.want.err, err)
  849. }
  850. // if errors are the same type but their contents do not match
  851. if err != nil && tc.want.err != nil {
  852. if !strings.Contains(err.Error(), tc.want.err.Error()) {
  853. t.Errorf("\nTesting SetSecret:\nName: %v\nReason: %v\nWant error: %v\nGot error got nil", name, tc.reason, tc.want.err)
  854. }
  855. }
  856. })
  857. }
  858. }
  859. func makeValidSecretStore() *esv1beta1.SecretStore {
  860. return &esv1beta1.SecretStore{
  861. ObjectMeta: metav1.ObjectMeta{
  862. Name: "aws-secret-store",
  863. Namespace: "default",
  864. },
  865. Spec: esv1beta1.SecretStoreSpec{
  866. Provider: &esv1beta1.SecretStoreProvider{
  867. AWS: &esv1beta1.AWSProvider{
  868. Service: esv1beta1.AWSServiceSecretsManager,
  869. Region: "eu-west-2",
  870. },
  871. },
  872. },
  873. }
  874. }
  875. func getTagSlice() []*awssm.Tag {
  876. tagKey1 := tagname1
  877. tagValue1 := tagvalue1
  878. tagKey2 := tagname2
  879. tagValue2 := tagvalue2
  880. return []*awssm.Tag{
  881. {
  882. Key: &tagKey1,
  883. Value: &tagValue1,
  884. },
  885. {
  886. Key: &tagKey2,
  887. Value: &tagValue2,
  888. },
  889. }
  890. }