secretsmanager_test.go 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443
  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. "reflect"
  18. "strings"
  19. "testing"
  20. "time"
  21. "github.com/aws/aws-sdk-go/aws"
  22. "github.com/aws/aws-sdk-go/aws/awserr"
  23. "github.com/aws/aws-sdk-go/aws/credentials"
  24. "github.com/aws/aws-sdk-go/aws/request"
  25. "github.com/aws/aws-sdk-go/aws/session"
  26. awssm "github.com/aws/aws-sdk-go/service/secretsmanager"
  27. "github.com/google/go-cmp/cmp"
  28. "github.com/stretchr/testify/assert"
  29. corev1 "k8s.io/api/core/v1"
  30. apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
  31. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  32. "k8s.io/utils/ptr"
  33. esv1beta1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1beta1"
  34. fakesm "github.com/external-secrets/external-secrets/pkg/provider/aws/secretsmanager/fake"
  35. "github.com/external-secrets/external-secrets/pkg/provider/aws/util"
  36. "github.com/external-secrets/external-secrets/pkg/provider/testing/fake"
  37. )
  38. type secretsManagerTestCase struct {
  39. fakeClient *fakesm.Client
  40. apiInput *awssm.GetSecretValueInput
  41. apiOutput *awssm.GetSecretValueOutput
  42. remoteRef *esv1beta1.ExternalSecretDataRemoteRef
  43. apiErr error
  44. expectError string
  45. expectedSecret string
  46. // for testing secretmap
  47. expectedData map[string][]byte
  48. // for testing caching
  49. expectedCounter *int
  50. }
  51. const unexpectedErrorString = "[%d] unexpected error: %s, expected: '%s'"
  52. const (
  53. tagname1 = "tagname1"
  54. tagvalue1 = "tagvalue1"
  55. tagname2 = "tagname2"
  56. tagvalue2 = "tagvalue2"
  57. fakeKey = "fake-key"
  58. )
  59. func makeValidSecretsManagerTestCase() *secretsManagerTestCase {
  60. smtc := secretsManagerTestCase{
  61. fakeClient: fakesm.NewClient(),
  62. apiInput: makeValidAPIInput(),
  63. remoteRef: makeValidRemoteRef(),
  64. apiOutput: makeValidAPIOutput(),
  65. apiErr: nil,
  66. expectError: "",
  67. expectedSecret: "",
  68. expectedData: map[string][]byte{},
  69. }
  70. smtc.fakeClient.WithValue(smtc.apiInput, smtc.apiOutput, smtc.apiErr)
  71. return &smtc
  72. }
  73. func makeValidRemoteRef() *esv1beta1.ExternalSecretDataRemoteRef {
  74. return &esv1beta1.ExternalSecretDataRemoteRef{
  75. Key: "/baz",
  76. Version: "AWSCURRENT",
  77. }
  78. }
  79. func makeValidAPIInput() *awssm.GetSecretValueInput {
  80. return &awssm.GetSecretValueInput{
  81. SecretId: aws.String("/baz"),
  82. VersionStage: aws.String("AWSCURRENT"),
  83. }
  84. }
  85. func makeValidAPIOutput() *awssm.GetSecretValueOutput {
  86. return &awssm.GetSecretValueOutput{
  87. SecretString: aws.String(""),
  88. }
  89. }
  90. func makeValidSecretsManagerTestCaseCustom(tweaks ...func(smtc *secretsManagerTestCase)) *secretsManagerTestCase {
  91. smtc := makeValidSecretsManagerTestCase()
  92. for _, fn := range tweaks {
  93. fn(smtc)
  94. }
  95. smtc.fakeClient.WithValue(smtc.apiInput, smtc.apiOutput, smtc.apiErr)
  96. return smtc
  97. }
  98. // This case can be shared by both GetSecret and GetSecretMap tests.
  99. // bad case: set apiErr.
  100. var setAPIErr = func(smtc *secretsManagerTestCase) {
  101. smtc.apiErr = errors.New("oh no")
  102. smtc.expectError = "oh no"
  103. }
  104. // test the sm<->aws interface
  105. // make sure correct values are passed and errors are handled accordingly.
  106. func TestSecretsManagerGetSecret(t *testing.T) {
  107. // good case: default version is set
  108. // key is passed in, output is sent back
  109. setSecretString := func(smtc *secretsManagerTestCase) {
  110. smtc.apiOutput.SecretString = aws.String("testtesttest")
  111. smtc.expectedSecret = "testtesttest"
  112. }
  113. // good case: extract property
  114. // Testing that the property exists in the SecretString
  115. setRemoteRefPropertyExistsInKey := func(smtc *secretsManagerTestCase) {
  116. smtc.remoteRef.Property = "/shmoo"
  117. smtc.apiOutput.SecretString = aws.String(`{"/shmoo": "bang"}`)
  118. smtc.expectedSecret = "bang"
  119. }
  120. // bad case: missing property
  121. setRemoteRefMissingProperty := func(smtc *secretsManagerTestCase) {
  122. smtc.remoteRef.Property = "INVALPROP"
  123. smtc.expectError = "key INVALPROP does not exist in secret"
  124. }
  125. // bad case: extract property failure due to invalid json
  126. setRemoteRefMissingPropertyInvalidJSON := func(smtc *secretsManagerTestCase) {
  127. smtc.remoteRef.Property = "INVALPROP"
  128. smtc.apiOutput.SecretString = aws.String(`------`)
  129. smtc.expectError = "key INVALPROP does not exist in secret"
  130. }
  131. // good case: set .SecretString to nil but set binary with value
  132. setSecretBinaryNotSecretString := func(smtc *secretsManagerTestCase) {
  133. smtc.apiOutput.SecretBinary = []byte("yesplease")
  134. // needs to be set as nil, empty quotes ("") is considered existing
  135. smtc.apiOutput.SecretString = nil
  136. smtc.expectedSecret = "yesplease"
  137. }
  138. // bad case: both .SecretString and .SecretBinary are nil
  139. setSecretBinaryAndSecretStringToNil := func(smtc *secretsManagerTestCase) {
  140. smtc.apiOutput.SecretBinary = nil
  141. smtc.apiOutput.SecretString = nil
  142. smtc.expectError = "no secret string nor binary for key"
  143. }
  144. // good case: secretOut.SecretBinary JSON parsing
  145. setNestedSecretValueJSONParsing := func(smtc *secretsManagerTestCase) {
  146. smtc.apiOutput.SecretString = nil
  147. smtc.apiOutput.SecretBinary = []byte(`{"foobar":{"baz":"nestedval"}}`)
  148. smtc.remoteRef.Property = "foobar.baz"
  149. smtc.expectedSecret = "nestedval"
  150. }
  151. // good case: secretOut.SecretBinary no JSON parsing if name on key
  152. setSecretValueWithDot := func(smtc *secretsManagerTestCase) {
  153. smtc.apiOutput.SecretString = nil
  154. smtc.apiOutput.SecretBinary = []byte(`{"foobar.baz":"nestedval"}`)
  155. smtc.remoteRef.Property = "foobar.baz"
  156. smtc.expectedSecret = "nestedval"
  157. }
  158. // good case: custom version stage set
  159. setCustomVersionStage := func(smtc *secretsManagerTestCase) {
  160. smtc.apiInput.VersionStage = aws.String("1234")
  161. smtc.remoteRef.Version = "1234"
  162. smtc.apiOutput.SecretString = aws.String("FOOBA!")
  163. smtc.expectedSecret = "FOOBA!"
  164. }
  165. // good case: custom version id set
  166. setCustomVersionID := func(smtc *secretsManagerTestCase) {
  167. smtc.apiInput.VersionStage = nil
  168. smtc.apiInput.VersionId = aws.String("1234-5678")
  169. smtc.remoteRef.Version = "uuid/1234-5678"
  170. smtc.apiOutput.SecretString = aws.String("myvalue")
  171. smtc.expectedSecret = "myvalue"
  172. }
  173. fetchMetadata := func(smtc *secretsManagerTestCase) {
  174. smtc.remoteRef.MetadataPolicy = esv1beta1.ExternalSecretMetadataPolicyFetch
  175. describeSecretOutput := &awssm.DescribeSecretOutput{
  176. Tags: getTagSlice(),
  177. }
  178. smtc.fakeClient.DescribeSecretWithContextFn = fakesm.NewDescribeSecretWithContextFn(describeSecretOutput, nil)
  179. jsonTags, _ := util.SecretTagsToJSONString(getTagSlice())
  180. smtc.apiOutput.SecretString = &jsonTags
  181. smtc.expectedSecret = jsonTags
  182. }
  183. fetchMetadataProperty := 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 = tagname2
  190. jsonTags, _ := util.SecretTagsToJSONString(getTagSlice())
  191. smtc.apiOutput.SecretString = &jsonTags
  192. smtc.expectedSecret = tagvalue2
  193. }
  194. failMetadataWrongProperty := func(smtc *secretsManagerTestCase) {
  195. smtc.remoteRef.MetadataPolicy = esv1beta1.ExternalSecretMetadataPolicyFetch
  196. describeSecretOutput := &awssm.DescribeSecretOutput{
  197. Tags: getTagSlice(),
  198. }
  199. smtc.fakeClient.DescribeSecretWithContextFn = fakesm.NewDescribeSecretWithContextFn(describeSecretOutput, nil)
  200. smtc.remoteRef.Property = "fail"
  201. jsonTags, _ := util.SecretTagsToJSONString(getTagSlice())
  202. smtc.apiOutput.SecretString = &jsonTags
  203. smtc.expectError = "key fail does not exist in secret /baz"
  204. }
  205. successCases := []*secretsManagerTestCase{
  206. makeValidSecretsManagerTestCase(),
  207. makeValidSecretsManagerTestCaseCustom(setSecretString),
  208. makeValidSecretsManagerTestCaseCustom(setRemoteRefPropertyExistsInKey),
  209. makeValidSecretsManagerTestCaseCustom(setRemoteRefMissingProperty),
  210. makeValidSecretsManagerTestCaseCustom(setRemoteRefMissingPropertyInvalidJSON),
  211. makeValidSecretsManagerTestCaseCustom(setSecretBinaryNotSecretString),
  212. makeValidSecretsManagerTestCaseCustom(setSecretBinaryAndSecretStringToNil),
  213. makeValidSecretsManagerTestCaseCustom(setNestedSecretValueJSONParsing),
  214. makeValidSecretsManagerTestCaseCustom(setSecretValueWithDot),
  215. makeValidSecretsManagerTestCaseCustom(setCustomVersionStage),
  216. makeValidSecretsManagerTestCaseCustom(setCustomVersionID),
  217. makeValidSecretsManagerTestCaseCustom(setAPIErr),
  218. makeValidSecretsManagerTestCaseCustom(fetchMetadata),
  219. makeValidSecretsManagerTestCaseCustom(fetchMetadataProperty),
  220. makeValidSecretsManagerTestCaseCustom(failMetadataWrongProperty),
  221. }
  222. for k, v := range successCases {
  223. sm := SecretsManager{
  224. cache: make(map[string]*awssm.GetSecretValueOutput),
  225. client: v.fakeClient,
  226. }
  227. out, err := sm.GetSecret(context.Background(), *v.remoteRef)
  228. if !ErrorContains(err, v.expectError) {
  229. t.Errorf(unexpectedErrorString, k, err.Error(), v.expectError)
  230. }
  231. if err == nil && string(out) != v.expectedSecret {
  232. t.Errorf("[%d] unexpected secret: expected %s, got %s", k, v.expectedSecret, string(out))
  233. }
  234. }
  235. }
  236. func TestCaching(t *testing.T) {
  237. fakeClient := fakesm.NewClient()
  238. // good case: first call, since we are using the same key, results should be cached and the counter should not go
  239. // over 1
  240. firstCall := func(smtc *secretsManagerTestCase) {
  241. smtc.apiOutput.SecretString = aws.String(`{"foo":"bar", "bar":"vodka"}`)
  242. smtc.remoteRef.Property = "foo"
  243. smtc.expectedSecret = "bar"
  244. smtc.expectedCounter = aws.Int(1)
  245. smtc.fakeClient = fakeClient
  246. }
  247. secondCall := func(smtc *secretsManagerTestCase) {
  248. smtc.apiOutput.SecretString = aws.String(`{"foo":"bar", "bar":"vodka"}`)
  249. smtc.remoteRef.Property = "bar"
  250. smtc.expectedSecret = "vodka"
  251. smtc.expectedCounter = aws.Int(1)
  252. smtc.fakeClient = fakeClient
  253. }
  254. notCachedCall := func(smtc *secretsManagerTestCase) {
  255. smtc.apiOutput.SecretString = aws.String(`{"sheldon":"bazinga", "bar":"foo"}`)
  256. smtc.remoteRef.Property = "sheldon"
  257. smtc.expectedSecret = "bazinga"
  258. smtc.expectedCounter = aws.Int(2)
  259. smtc.fakeClient = fakeClient
  260. smtc.apiInput.SecretId = aws.String("xyz")
  261. smtc.remoteRef.Key = "xyz" // it should reset the cache since the key is different
  262. }
  263. cachedCases := []*secretsManagerTestCase{
  264. makeValidSecretsManagerTestCaseCustom(firstCall),
  265. makeValidSecretsManagerTestCaseCustom(firstCall),
  266. makeValidSecretsManagerTestCaseCustom(secondCall),
  267. makeValidSecretsManagerTestCaseCustom(notCachedCall),
  268. }
  269. sm := SecretsManager{
  270. cache: make(map[string]*awssm.GetSecretValueOutput),
  271. }
  272. for k, v := range cachedCases {
  273. sm.client = v.fakeClient
  274. out, err := sm.GetSecret(context.Background(), *v.remoteRef)
  275. if !ErrorContains(err, v.expectError) {
  276. t.Errorf(unexpectedErrorString, k, err.Error(), v.expectError)
  277. }
  278. if err == nil && string(out) != v.expectedSecret {
  279. t.Errorf("[%d] unexpected secret: expected %s, got %s", k, v.expectedSecret, string(out))
  280. }
  281. if v.expectedCounter != nil && v.fakeClient.ExecutionCounter != *v.expectedCounter {
  282. t.Errorf("[%d] unexpected counter value: expected %d, got %d", k, v.expectedCounter, v.fakeClient.ExecutionCounter)
  283. }
  284. }
  285. }
  286. func TestGetSecretMap(t *testing.T) {
  287. // good case: default version & deserialization
  288. setDeserialization := func(smtc *secretsManagerTestCase) {
  289. smtc.apiOutput.SecretString = aws.String(`{"foo":"bar"}`)
  290. smtc.expectedData["foo"] = []byte("bar")
  291. }
  292. // good case: nested json
  293. setNestedJSON := func(smtc *secretsManagerTestCase) {
  294. smtc.apiOutput.SecretString = aws.String(`{"foobar":{"baz":"nestedval"}}`)
  295. smtc.expectedData["foobar"] = []byte("{\"baz\":\"nestedval\"}")
  296. }
  297. // good case: caching
  298. cachedMap := func(smtc *secretsManagerTestCase) {
  299. smtc.apiOutput.SecretString = aws.String(`{"foo":"bar", "plus": "one"}`)
  300. smtc.expectedData["foo"] = []byte("bar")
  301. smtc.expectedData["plus"] = []byte("one")
  302. smtc.expectedCounter = aws.Int(1)
  303. }
  304. // bad case: invalid json
  305. setInvalidJSON := func(smtc *secretsManagerTestCase) {
  306. smtc.apiOutput.SecretString = aws.String(`-----------------`)
  307. smtc.expectError = "unable to unmarshal secret"
  308. }
  309. successCases := []*secretsManagerTestCase{
  310. makeValidSecretsManagerTestCaseCustom(setDeserialization),
  311. makeValidSecretsManagerTestCaseCustom(setNestedJSON),
  312. makeValidSecretsManagerTestCaseCustom(setAPIErr),
  313. makeValidSecretsManagerTestCaseCustom(setInvalidJSON),
  314. makeValidSecretsManagerTestCaseCustom(cachedMap),
  315. }
  316. for k, v := range successCases {
  317. sm := SecretsManager{
  318. cache: make(map[string]*awssm.GetSecretValueOutput),
  319. client: v.fakeClient,
  320. }
  321. out, err := sm.GetSecretMap(context.Background(), *v.remoteRef)
  322. if !ErrorContains(err, v.expectError) {
  323. t.Errorf(unexpectedErrorString, k, err.Error(), v.expectError)
  324. }
  325. if err == nil && !cmp.Equal(out, v.expectedData) {
  326. t.Errorf("[%d] unexpected secret data: expected %#v, got %#v", k, v.expectedData, out)
  327. }
  328. if v.expectedCounter != nil && v.fakeClient.ExecutionCounter != *v.expectedCounter {
  329. t.Errorf("[%d] unexpected counter value: expected %d, got %d", k, v.expectedCounter, v.fakeClient.ExecutionCounter)
  330. }
  331. }
  332. }
  333. func ErrorContains(out error, want string) bool {
  334. if out == nil {
  335. return want == ""
  336. }
  337. if want == "" {
  338. return false
  339. }
  340. return strings.Contains(out.Error(), want)
  341. }
  342. func TestSetSecret(t *testing.T) {
  343. managedBy := managedBy
  344. notManagedBy := "not-managed-by"
  345. secretKey := "fake-secret-key"
  346. secretValue := []byte("fake-value")
  347. fakeSecret := &corev1.Secret{
  348. Data: map[string][]byte{
  349. secretKey: secretValue,
  350. },
  351. }
  352. externalSecrets := externalSecrets
  353. noPermission := errors.New("no permission")
  354. arn := "arn:aws:secretsmanager:us-east-1:702902267788:secret:foo-bar5-Robbgh"
  355. getSecretCorrectErr := awssm.ResourceNotFoundException{}
  356. getSecretWrongErr := awssm.InvalidRequestException{}
  357. secretOutput := &awssm.CreateSecretOutput{
  358. ARN: &arn,
  359. }
  360. externalSecretsTag := []*awssm.Tag{
  361. {
  362. Key: &managedBy,
  363. Value: &externalSecrets,
  364. },
  365. }
  366. externalSecretsTagFaulty := []*awssm.Tag{
  367. {
  368. Key: &notManagedBy,
  369. Value: &externalSecrets,
  370. },
  371. }
  372. tagSecretOutput := &awssm.DescribeSecretOutput{
  373. ARN: &arn,
  374. Tags: externalSecretsTag,
  375. }
  376. tagSecretOutputFaulty := &awssm.DescribeSecretOutput{
  377. ARN: &arn,
  378. Tags: externalSecretsTagFaulty,
  379. }
  380. initialVersion := "00000000-0000-0000-0000-000000000001"
  381. defaultVersion := "00000000-0000-0000-0000-000000000002"
  382. defaultUpdatedVersion := "00000000-0000-0000-0000-000000000003"
  383. randomUUIDVersion := "c2812e8d-84ce-4858-abec-7163d8ab312b"
  384. randomUUIDVersionIncremented := "c2812e8d-84ce-4858-abec-7163d8ab312c"
  385. unparsableVersion := "IAM UNPARSABLE"
  386. secretValueOutput := &awssm.GetSecretValueOutput{
  387. ARN: &arn,
  388. VersionId: &defaultVersion,
  389. }
  390. secretValueOutput2 := &awssm.GetSecretValueOutput{
  391. ARN: &arn,
  392. SecretBinary: secretValue,
  393. VersionId: &defaultVersion,
  394. }
  395. type params struct {
  396. s string
  397. b []byte
  398. version *string
  399. }
  400. secretValueOutputFrom := func(params params) *awssm.GetSecretValueOutput {
  401. var version *string
  402. if params.version == nil {
  403. version = &defaultVersion
  404. } else {
  405. version = params.version
  406. }
  407. return &awssm.GetSecretValueOutput{
  408. ARN: &arn,
  409. SecretString: &params.s,
  410. SecretBinary: params.b,
  411. VersionId: version,
  412. }
  413. }
  414. blankSecretValueOutput := &awssm.GetSecretValueOutput{}
  415. putSecretOutput := &awssm.PutSecretValueOutput{
  416. ARN: &arn,
  417. }
  418. pushSecretDataWithoutProperty := fake.PushSecretData{SecretKey: secretKey, RemoteKey: fakeKey, Property: ""}
  419. pushSecretDataWithoutSecretKey := fake.PushSecretData{RemoteKey: fakeKey, Property: ""}
  420. pushSecretDataWithMetadata := fake.PushSecretData{SecretKey: secretKey, RemoteKey: fakeKey, Property: "", Metadata: &apiextensionsv1.JSON{
  421. Raw: []byte(`{"secretPushFormat": "string"}`),
  422. }}
  423. pushSecretDataWithProperty := fake.PushSecretData{SecretKey: secretKey, RemoteKey: fakeKey, Property: "other-fake-property"}
  424. type args struct {
  425. store *esv1beta1.AWSProvider
  426. client fakesm.Client
  427. pushSecretData fake.PushSecretData
  428. }
  429. type want struct {
  430. err error
  431. }
  432. tests := map[string]struct {
  433. reason string
  434. args args
  435. want want
  436. }{
  437. "SetSecretSucceedsWithExistingSecret": {
  438. reason: "a secret can be pushed to aws secrets manager when it already exists",
  439. args: args{
  440. store: makeValidSecretStore().Spec.Provider.AWS,
  441. client: fakesm.Client{
  442. GetSecretValueWithContextFn: fakesm.NewGetSecretValueWithContextFn(secretValueOutput, nil),
  443. CreateSecretWithContextFn: fakesm.NewCreateSecretWithContextFn(secretOutput, nil),
  444. PutSecretValueWithContextFn: fakesm.NewPutSecretValueWithContextFn(putSecretOutput, nil),
  445. DescribeSecretWithContextFn: fakesm.NewDescribeSecretWithContextFn(tagSecretOutput, nil),
  446. },
  447. pushSecretData: pushSecretDataWithoutProperty,
  448. },
  449. want: want{
  450. err: nil,
  451. },
  452. },
  453. "SetSecretSucceedsWithoutSecretKey": {
  454. reason: "a secret can be pushed to aws secrets manager without secret key",
  455. args: args{
  456. store: makeValidSecretStore().Spec.Provider.AWS,
  457. client: fakesm.Client{
  458. GetSecretValueWithContextFn: fakesm.NewGetSecretValueWithContextFn(secretValueOutput, nil),
  459. CreateSecretWithContextFn: fakesm.NewCreateSecretWithContextFn(secretOutput, nil),
  460. PutSecretValueWithContextFn: fakesm.NewPutSecretValueWithContextFn(putSecretOutput, nil),
  461. DescribeSecretWithContextFn: fakesm.NewDescribeSecretWithContextFn(tagSecretOutput, nil),
  462. },
  463. pushSecretData: pushSecretDataWithoutSecretKey,
  464. },
  465. want: want{
  466. err: nil,
  467. },
  468. },
  469. "SetSecretSucceedsWithExistingSecretAndStringFormat": {
  470. reason: "a secret can be pushed to aws secrets manager when it already exists",
  471. args: args{
  472. store: makeValidSecretStore().Spec.Provider.AWS,
  473. client: fakesm.Client{
  474. GetSecretValueWithContextFn: fakesm.NewGetSecretValueWithContextFn(secretValueOutput, nil),
  475. CreateSecretWithContextFn: fakesm.NewCreateSecretWithContextFn(secretOutput, nil),
  476. PutSecretValueWithContextFn: fakesm.NewPutSecretValueWithContextFn(putSecretOutput, nil),
  477. DescribeSecretWithContextFn: fakesm.NewDescribeSecretWithContextFn(tagSecretOutput, nil),
  478. },
  479. pushSecretData: pushSecretDataWithMetadata,
  480. },
  481. want: want{
  482. err: nil,
  483. },
  484. },
  485. "SetSecretSucceedsWithNewSecret": {
  486. reason: "a secret can be pushed to aws secrets manager if it doesn't already exist",
  487. args: args{
  488. store: makeValidSecretStore().Spec.Provider.AWS,
  489. client: fakesm.Client{
  490. GetSecretValueWithContextFn: fakesm.NewGetSecretValueWithContextFn(blankSecretValueOutput, &getSecretCorrectErr),
  491. CreateSecretWithContextFn: fakesm.NewCreateSecretWithContextFn(secretOutput, nil),
  492. },
  493. pushSecretData: pushSecretDataWithoutProperty,
  494. },
  495. want: want{
  496. err: nil,
  497. },
  498. },
  499. "SetSecretWithPropertySucceedsWithNewSecret": {
  500. reason: "if a new secret is pushed to aws sm and a pushSecretData property is specified, create a json secret with the pushSecretData property as a key",
  501. args: args{
  502. store: makeValidSecretStore().Spec.Provider.AWS,
  503. client: fakesm.Client{
  504. GetSecretValueWithContextFn: fakesm.NewGetSecretValueWithContextFn(blankSecretValueOutput, &getSecretCorrectErr),
  505. CreateSecretWithContextFn: fakesm.NewCreateSecretWithContextFn(secretOutput, nil, []byte(`{"other-fake-property":"fake-value"}`)),
  506. },
  507. pushSecretData: pushSecretDataWithProperty,
  508. },
  509. want: want{
  510. err: nil,
  511. },
  512. },
  513. "SetSecretWithPropertySucceedsWithExistingSecretAndNewPropertyBinary": {
  514. reason: "when a pushSecretData property is specified, this property will be added to the sm secret if it is currently absent (sm secret is binary)",
  515. args: args{
  516. store: makeValidSecretStore().Spec.Provider.AWS,
  517. client: fakesm.Client{
  518. GetSecretValueWithContextFn: fakesm.NewGetSecretValueWithContextFn(secretValueOutputFrom(params{b: []byte((`{"fake-property":"fake-value"}`))}), nil),
  519. DescribeSecretWithContextFn: fakesm.NewDescribeSecretWithContextFn(tagSecretOutput, nil),
  520. PutSecretValueWithContextFn: fakesm.NewPutSecretValueWithContextFn(putSecretOutput, nil, fakesm.ExpectedPutSecretValueInput{
  521. SecretBinary: []byte(`{"fake-property":"fake-value","other-fake-property":"fake-value"}`),
  522. Version: &defaultUpdatedVersion,
  523. }),
  524. },
  525. pushSecretData: pushSecretDataWithProperty,
  526. },
  527. want: want{
  528. err: nil,
  529. },
  530. },
  531. "SetSecretWithPropertySucceedsWithExistingSecretAndRandomUUIDVersion": {
  532. 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",
  533. args: args{
  534. store: makeValidSecretStore().Spec.Provider.AWS,
  535. client: fakesm.Client{
  536. GetSecretValueWithContextFn: fakesm.NewGetSecretValueWithContextFn(secretValueOutputFrom(params{
  537. b: []byte((`{"fake-property":"fake-value"}`)),
  538. version: &randomUUIDVersion,
  539. }), nil),
  540. DescribeSecretWithContextFn: fakesm.NewDescribeSecretWithContextFn(tagSecretOutput, nil),
  541. PutSecretValueWithContextFn: fakesm.NewPutSecretValueWithContextFn(putSecretOutput, nil, fakesm.ExpectedPutSecretValueInput{
  542. SecretBinary: []byte(`{"fake-property":"fake-value","other-fake-property":"fake-value"}`),
  543. Version: &randomUUIDVersionIncremented,
  544. }),
  545. },
  546. pushSecretData: pushSecretDataWithProperty,
  547. },
  548. want: want{
  549. err: nil,
  550. },
  551. },
  552. "SetSecretWithPropertySucceedsWithExistingSecretAndVersionThatCantBeParsed": {
  553. reason: "A manually set secret version doesn't have to be a UUID, we only support UUID secret versions though",
  554. args: args{
  555. store: makeValidSecretStore().Spec.Provider.AWS,
  556. client: fakesm.Client{
  557. GetSecretValueWithContextFn: fakesm.NewGetSecretValueWithContextFn(secretValueOutputFrom(params{
  558. b: []byte((`{"fake-property":"fake-value"}`)),
  559. version: &unparsableVersion,
  560. }), nil),
  561. DescribeSecretWithContextFn: fakesm.NewDescribeSecretWithContextFn(tagSecretOutput, nil),
  562. PutSecretValueWithContextFn: fakesm.NewPutSecretValueWithContextFn(putSecretOutput, nil, fakesm.ExpectedPutSecretValueInput{
  563. SecretBinary: []byte(`{"fake-property":"fake-value","other-fake-property":"fake-value"}`),
  564. Version: &initialVersion,
  565. }),
  566. },
  567. pushSecretData: pushSecretDataWithProperty,
  568. },
  569. want: want{
  570. err: fmt.Errorf("expected secret version in AWS SSM to be a UUID but got '%s'", unparsableVersion),
  571. },
  572. },
  573. "SetSecretWithPropertySucceedsWithExistingSecretAndAbsentVersion": {
  574. reason: "When a secret version is not specified, set it to 1",
  575. args: args{
  576. store: makeValidSecretStore().Spec.Provider.AWS,
  577. client: fakesm.Client{
  578. GetSecretValueWithContextFn: fakesm.NewGetSecretValueWithContextFn(&awssm.GetSecretValueOutput{
  579. ARN: &arn,
  580. SecretBinary: []byte((`{"fake-property":"fake-value"}`)),
  581. }, nil),
  582. DescribeSecretWithContextFn: fakesm.NewDescribeSecretWithContextFn(tagSecretOutput, nil),
  583. PutSecretValueWithContextFn: fakesm.NewPutSecretValueWithContextFn(putSecretOutput, nil, fakesm.ExpectedPutSecretValueInput{
  584. SecretBinary: []byte(`{"fake-property":"fake-value","other-fake-property":"fake-value"}`),
  585. Version: &initialVersion,
  586. }),
  587. },
  588. pushSecretData: pushSecretDataWithProperty,
  589. },
  590. want: want{
  591. err: nil,
  592. },
  593. },
  594. "SetSecretWithPropertySucceedsWithExistingSecretAndNewPropertyString": {
  595. reason: "when a pushSecretData property is specified, this property will be added to the sm secret if it is currently absent (sm secret is a string)",
  596. args: args{
  597. store: makeValidSecretStore().Spec.Provider.AWS,
  598. client: fakesm.Client{
  599. GetSecretValueWithContextFn: fakesm.NewGetSecretValueWithContextFn(secretValueOutputFrom(params{s: `{"fake-property":"fake-value"}`}), nil),
  600. DescribeSecretWithContextFn: fakesm.NewDescribeSecretWithContextFn(tagSecretOutput, nil),
  601. PutSecretValueWithContextFn: fakesm.NewPutSecretValueWithContextFn(putSecretOutput, nil, fakesm.ExpectedPutSecretValueInput{
  602. SecretBinary: []byte(`{"fake-property":"fake-value","other-fake-property":"fake-value"}`),
  603. Version: &defaultUpdatedVersion,
  604. }),
  605. },
  606. pushSecretData: pushSecretDataWithProperty,
  607. },
  608. want: want{
  609. err: nil,
  610. },
  611. },
  612. "SetSecretWithPropertySucceedsWithExistingSecretAndNewPropertyWithDot": {
  613. reason: "when a pushSecretData property is specified, this property will be added to the sm secret if it is currently absent (pushSecretData property is a sub-object)",
  614. args: args{
  615. store: makeValidSecretStore().Spec.Provider.AWS,
  616. client: fakesm.Client{
  617. GetSecretValueWithContextFn: fakesm.NewGetSecretValueWithContextFn(secretValueOutputFrom(params{s: `{"fake-property":{"fake-property":"fake-value"}}`}), nil),
  618. DescribeSecretWithContextFn: fakesm.NewDescribeSecretWithContextFn(tagSecretOutput, nil),
  619. PutSecretValueWithContextFn: fakesm.NewPutSecretValueWithContextFn(putSecretOutput, nil, fakesm.ExpectedPutSecretValueInput{
  620. SecretBinary: []byte(`{"fake-property":{"fake-property":"fake-value","other-fake-property":"fake-value"}}`),
  621. Version: &defaultUpdatedVersion,
  622. }),
  623. },
  624. pushSecretData: fake.PushSecretData{SecretKey: secretKey, RemoteKey: fakeKey, Property: "fake-property.other-fake-property"},
  625. },
  626. want: want{
  627. err: nil,
  628. },
  629. },
  630. "SetSecretWithPropertyFailsExistingNonJsonSecret": {
  631. reason: "setting a pushSecretData property is only supported for json secrets",
  632. args: args{
  633. store: makeValidSecretStore().Spec.Provider.AWS,
  634. client: fakesm.Client{
  635. GetSecretValueWithContextFn: fakesm.NewGetSecretValueWithContextFn(secretValueOutputFrom(params{s: `non-json-secret`}), nil),
  636. DescribeSecretWithContextFn: fakesm.NewDescribeSecretWithContextFn(tagSecretOutput, nil),
  637. },
  638. pushSecretData: pushSecretDataWithProperty,
  639. },
  640. want: want{
  641. err: errors.New("PushSecret for aws secrets manager with a pushSecretData property requires a json secret"),
  642. },
  643. },
  644. "SetSecretCreateSecretFails": {
  645. reason: "CreateSecretWithContext returns an error if it fails",
  646. args: args{
  647. store: makeValidSecretStore().Spec.Provider.AWS,
  648. client: fakesm.Client{
  649. GetSecretValueWithContextFn: fakesm.NewGetSecretValueWithContextFn(blankSecretValueOutput, &getSecretCorrectErr),
  650. CreateSecretWithContextFn: fakesm.NewCreateSecretWithContextFn(nil, noPermission),
  651. },
  652. pushSecretData: pushSecretDataWithoutProperty,
  653. },
  654. want: want{
  655. err: noPermission,
  656. },
  657. },
  658. "SetSecretGetSecretFails": {
  659. reason: "GetSecretValueWithContext returns an error if it fails",
  660. args: args{
  661. store: makeValidSecretStore().Spec.Provider.AWS,
  662. client: fakesm.Client{
  663. GetSecretValueWithContextFn: fakesm.NewGetSecretValueWithContextFn(blankSecretValueOutput, noPermission),
  664. },
  665. pushSecretData: pushSecretDataWithoutProperty,
  666. },
  667. want: want{
  668. err: noPermission,
  669. },
  670. },
  671. "SetSecretWillNotPushSameSecret": {
  672. reason: "secret with the same value will not be pushed",
  673. args: args{
  674. store: makeValidSecretStore().Spec.Provider.AWS,
  675. client: fakesm.Client{
  676. GetSecretValueWithContextFn: fakesm.NewGetSecretValueWithContextFn(secretValueOutput2, nil),
  677. DescribeSecretWithContextFn: fakesm.NewDescribeSecretWithContextFn(tagSecretOutput, nil),
  678. },
  679. pushSecretData: pushSecretDataWithoutProperty,
  680. },
  681. want: want{
  682. err: nil,
  683. },
  684. },
  685. "SetSecretPutSecretValueFails": {
  686. reason: "PutSecretValueWithContext returns an error if it fails",
  687. args: args{
  688. store: makeValidSecretStore().Spec.Provider.AWS,
  689. client: fakesm.Client{
  690. GetSecretValueWithContextFn: fakesm.NewGetSecretValueWithContextFn(secretValueOutput, nil),
  691. PutSecretValueWithContextFn: fakesm.NewPutSecretValueWithContextFn(nil, noPermission),
  692. DescribeSecretWithContextFn: fakesm.NewDescribeSecretWithContextFn(tagSecretOutput, nil),
  693. },
  694. pushSecretData: pushSecretDataWithoutProperty,
  695. },
  696. want: want{
  697. err: noPermission,
  698. },
  699. },
  700. "SetSecretWrongGetSecretErrFails": {
  701. reason: "GetSecretValueWithContext errors out when anything except awssm.ErrCodeResourceNotFoundException",
  702. args: args{
  703. store: makeValidSecretStore().Spec.Provider.AWS,
  704. client: fakesm.Client{
  705. GetSecretValueWithContextFn: fakesm.NewGetSecretValueWithContextFn(blankSecretValueOutput, &getSecretWrongErr),
  706. },
  707. pushSecretData: pushSecretDataWithoutProperty,
  708. },
  709. want: want{
  710. err: &getSecretWrongErr,
  711. },
  712. },
  713. "SetSecretDescribeSecretFails": {
  714. reason: "secret cannot be described",
  715. args: args{
  716. store: makeValidSecretStore().Spec.Provider.AWS,
  717. client: fakesm.Client{
  718. GetSecretValueWithContextFn: fakesm.NewGetSecretValueWithContextFn(secretValueOutput, nil),
  719. DescribeSecretWithContextFn: fakesm.NewDescribeSecretWithContextFn(nil, noPermission),
  720. },
  721. pushSecretData: pushSecretDataWithoutProperty,
  722. },
  723. want: want{
  724. err: noPermission,
  725. },
  726. },
  727. "SetSecretDoesNotOverwriteUntaggedSecret": {
  728. reason: "secret cannot be described",
  729. args: args{
  730. store: makeValidSecretStore().Spec.Provider.AWS,
  731. client: fakesm.Client{
  732. GetSecretValueWithContextFn: fakesm.NewGetSecretValueWithContextFn(secretValueOutput, nil),
  733. DescribeSecretWithContextFn: fakesm.NewDescribeSecretWithContextFn(tagSecretOutputFaulty, nil),
  734. },
  735. pushSecretData: pushSecretDataWithoutProperty,
  736. },
  737. want: want{
  738. err: errors.New("secret not managed by external-secrets"),
  739. },
  740. },
  741. }
  742. for name, tc := range tests {
  743. t.Run(name, func(t *testing.T) {
  744. sm := SecretsManager{
  745. client: &tc.args.client,
  746. }
  747. err := sm.PushSecret(context.Background(), fakeSecret, tc.args.pushSecretData)
  748. // Error nil XOR tc.want.err nil
  749. if ((err == nil) || (tc.want.err == nil)) && !((err == nil) && (tc.want.err == nil)) {
  750. t.Errorf("\nTesting SetSecret:\nName: %v\nReason: %v\nWant error: %v\nGot error: %v", name, tc.reason, tc.want.err, err)
  751. }
  752. // if errors are the same type but their contents do not match
  753. if err != nil && tc.want.err != nil {
  754. if !strings.Contains(err.Error(), tc.want.err.Error()) {
  755. t.Errorf("\nTesting SetSecret:\nName: %v\nReason: %v\nWant error: %v\nGot error got nil", name, tc.reason, tc.want.err)
  756. }
  757. }
  758. })
  759. }
  760. }
  761. func TestDeleteSecret(t *testing.T) {
  762. fakeClient := fakesm.Client{}
  763. managed := managedBy
  764. manager := externalSecrets
  765. secretTag := awssm.Tag{
  766. Key: &managed,
  767. Value: &manager,
  768. }
  769. type args struct {
  770. client fakesm.Client
  771. config esv1beta1.SecretsManager
  772. getSecretOutput *awssm.GetSecretValueOutput
  773. describeSecretOutput *awssm.DescribeSecretOutput
  774. deleteSecretOutput *awssm.DeleteSecretOutput
  775. getSecretErr error
  776. describeSecretErr error
  777. deleteSecretErr error
  778. }
  779. type want struct {
  780. err error
  781. }
  782. type testCase struct {
  783. args args
  784. want want
  785. reason string
  786. }
  787. tests := map[string]testCase{
  788. "Deletes Successfully": {
  789. args: args{
  790. client: fakeClient,
  791. config: esv1beta1.SecretsManager{},
  792. getSecretOutput: &awssm.GetSecretValueOutput{},
  793. describeSecretOutput: &awssm.DescribeSecretOutput{
  794. Tags: []*awssm.Tag{&secretTag},
  795. },
  796. deleteSecretOutput: &awssm.DeleteSecretOutput{},
  797. getSecretErr: nil,
  798. describeSecretErr: nil,
  799. deleteSecretErr: nil,
  800. },
  801. want: want{
  802. err: nil,
  803. },
  804. reason: "",
  805. },
  806. "Deletes Successfully with ForceDeleteWithoutRecovery": {
  807. args: args{
  808. client: fakeClient,
  809. config: esv1beta1.SecretsManager{
  810. ForceDeleteWithoutRecovery: true,
  811. },
  812. getSecretOutput: &awssm.GetSecretValueOutput{},
  813. describeSecretOutput: &awssm.DescribeSecretOutput{
  814. Tags: []*awssm.Tag{&secretTag},
  815. },
  816. deleteSecretOutput: &awssm.DeleteSecretOutput{
  817. DeletionDate: aws.Time(time.Now()),
  818. },
  819. getSecretErr: nil,
  820. describeSecretErr: nil,
  821. deleteSecretErr: nil,
  822. },
  823. want: want{
  824. err: nil,
  825. },
  826. reason: "",
  827. },
  828. "Not Managed by ESO": {
  829. args: args{
  830. client: fakeClient,
  831. config: esv1beta1.SecretsManager{},
  832. getSecretOutput: &awssm.GetSecretValueOutput{},
  833. describeSecretOutput: &awssm.DescribeSecretOutput{
  834. Tags: []*awssm.Tag{},
  835. },
  836. deleteSecretOutput: &awssm.DeleteSecretOutput{},
  837. getSecretErr: nil,
  838. describeSecretErr: nil,
  839. deleteSecretErr: nil,
  840. },
  841. want: want{
  842. err: nil,
  843. },
  844. reason: "",
  845. },
  846. "Invalid Recovery Window": {
  847. args: args{
  848. client: fakesm.Client{},
  849. config: esv1beta1.SecretsManager{
  850. RecoveryWindowInDays: 1,
  851. },
  852. getSecretOutput: &awssm.GetSecretValueOutput{},
  853. describeSecretOutput: &awssm.DescribeSecretOutput{
  854. Tags: []*awssm.Tag{&secretTag},
  855. },
  856. deleteSecretOutput: &awssm.DeleteSecretOutput{},
  857. getSecretErr: nil,
  858. describeSecretErr: nil,
  859. deleteSecretErr: nil,
  860. },
  861. want: want{
  862. err: errors.New("invalid DeleteSecretInput: RecoveryWindowInDays must be between 7 and 30 days"),
  863. },
  864. reason: "",
  865. },
  866. "RecoveryWindowInDays is supplied with ForceDeleteWithoutRecovery": {
  867. args: args{
  868. client: fakesm.Client{},
  869. config: esv1beta1.SecretsManager{
  870. RecoveryWindowInDays: 7,
  871. ForceDeleteWithoutRecovery: true,
  872. },
  873. getSecretOutput: &awssm.GetSecretValueOutput{},
  874. describeSecretOutput: &awssm.DescribeSecretOutput{
  875. Tags: []*awssm.Tag{&secretTag},
  876. },
  877. deleteSecretOutput: &awssm.DeleteSecretOutput{},
  878. getSecretErr: nil,
  879. describeSecretErr: nil,
  880. deleteSecretErr: nil,
  881. },
  882. want: want{
  883. err: errors.New("invalid DeleteSecretInput: ForceDeleteWithoutRecovery conflicts with RecoveryWindowInDays"),
  884. },
  885. reason: "",
  886. },
  887. "Failed to get Tags": {
  888. args: args{
  889. client: fakeClient,
  890. config: esv1beta1.SecretsManager{},
  891. getSecretOutput: &awssm.GetSecretValueOutput{},
  892. describeSecretOutput: nil,
  893. deleteSecretOutput: nil,
  894. getSecretErr: nil,
  895. describeSecretErr: errors.New("failed to get tags"),
  896. deleteSecretErr: nil,
  897. },
  898. want: want{
  899. err: errors.New("failed to get tags"),
  900. },
  901. reason: "",
  902. },
  903. "Secret Not Found": {
  904. args: args{
  905. client: fakeClient,
  906. config: esv1beta1.SecretsManager{},
  907. getSecretOutput: nil,
  908. describeSecretOutput: nil,
  909. deleteSecretOutput: nil,
  910. getSecretErr: awserr.New(awssm.ErrCodeResourceNotFoundException, "not here, sorry dude", nil),
  911. describeSecretErr: nil,
  912. deleteSecretErr: nil,
  913. },
  914. want: want{
  915. err: nil,
  916. },
  917. },
  918. "Not expected AWS error": {
  919. args: args{
  920. client: fakeClient,
  921. config: esv1beta1.SecretsManager{},
  922. getSecretOutput: nil,
  923. describeSecretOutput: nil,
  924. deleteSecretOutput: nil,
  925. getSecretErr: awserr.New(awssm.ErrCodeEncryptionFailure, "aws unavailable", nil),
  926. describeSecretErr: nil,
  927. deleteSecretErr: nil,
  928. },
  929. want: want{
  930. err: errors.New("aws unavailable"),
  931. },
  932. },
  933. "unexpected error": {
  934. args: args{
  935. client: fakeClient,
  936. config: esv1beta1.SecretsManager{},
  937. getSecretOutput: nil,
  938. describeSecretOutput: nil,
  939. deleteSecretOutput: nil,
  940. getSecretErr: errors.New("timeout"),
  941. describeSecretErr: nil,
  942. deleteSecretErr: nil,
  943. },
  944. want: want{
  945. err: errors.New("timeout"),
  946. },
  947. },
  948. }
  949. for name, tc := range tests {
  950. t.Run(name, func(t *testing.T) {
  951. ref := fake.PushSecretData{RemoteKey: fakeKey}
  952. sm := SecretsManager{
  953. client: &tc.args.client,
  954. config: &tc.args.config,
  955. }
  956. tc.args.client.GetSecretValueWithContextFn = fakesm.NewGetSecretValueWithContextFn(tc.args.getSecretOutput, tc.args.getSecretErr)
  957. tc.args.client.DescribeSecretWithContextFn = fakesm.NewDescribeSecretWithContextFn(tc.args.describeSecretOutput, tc.args.describeSecretErr)
  958. tc.args.client.DeleteSecretWithContextFn = fakesm.NewDeleteSecretWithContextFn(tc.args.deleteSecretOutput, tc.args.deleteSecretErr)
  959. err := sm.DeleteSecret(context.TODO(), ref)
  960. t.Logf("DeleteSecret error: %v", err)
  961. // Error nil XOR tc.want.err nil
  962. if ((err == nil) || (tc.want.err == nil)) && !((err == nil) && (tc.want.err == nil)) {
  963. t.Errorf("\nTesting DeleteSecret:\nName: %v\nReason: %v\nWant error: %v\nGot error: %v", name, tc.reason, tc.want.err, err)
  964. }
  965. // if errors are the same type but their contents do not match
  966. if err != nil && tc.want.err != nil {
  967. if !strings.Contains(err.Error(), tc.want.err.Error()) {
  968. t.Errorf("\nTesting DeleteSecret:\nName: %v\nReason: %v\nWant error: %v\nGot error got nil", name, tc.reason, tc.want.err)
  969. }
  970. }
  971. })
  972. }
  973. }
  974. func makeValidSecretStore() *esv1beta1.SecretStore {
  975. return &esv1beta1.SecretStore{
  976. ObjectMeta: metav1.ObjectMeta{
  977. Name: "aws-secret-store",
  978. Namespace: "default",
  979. },
  980. Spec: esv1beta1.SecretStoreSpec{
  981. Provider: &esv1beta1.SecretStoreProvider{
  982. AWS: &esv1beta1.AWSProvider{
  983. Service: esv1beta1.AWSServiceSecretsManager,
  984. Region: "eu-west-2",
  985. },
  986. },
  987. },
  988. }
  989. }
  990. func getTagSlice() []*awssm.Tag {
  991. tagKey1 := tagname1
  992. tagValue1 := tagvalue1
  993. tagKey2 := tagname2
  994. tagValue2 := tagvalue2
  995. return []*awssm.Tag{
  996. {
  997. Key: &tagKey1,
  998. Value: &tagValue1,
  999. },
  1000. {
  1001. Key: &tagKey2,
  1002. Value: &tagValue2,
  1003. },
  1004. }
  1005. }
  1006. func TestSecretsManagerGetAllSecrets(t *testing.T) {
  1007. ctx := context.Background()
  1008. errBoom := errors.New("boom")
  1009. secretName := "my-secret"
  1010. secretVersion := "AWSCURRENT"
  1011. secretPath := "/path/to/secret"
  1012. secretValue := "secret value"
  1013. secretTags := map[string]string{
  1014. "foo": "bar",
  1015. }
  1016. // Test cases
  1017. testCases := []struct {
  1018. name string
  1019. ref esv1beta1.ExternalSecretFind
  1020. secretName string
  1021. secretVersion string
  1022. secretValue string
  1023. batchGetSecretValueWithContextFn func(aws.Context, *awssm.BatchGetSecretValueInput, ...request.Option) (*awssm.BatchGetSecretValueOutput, error)
  1024. listSecretsFn func(ctx context.Context, input *awssm.ListSecretsInput, opts ...request.Option) (*awssm.ListSecretsOutput, error)
  1025. expectedData map[string][]byte
  1026. expectedError string
  1027. }{
  1028. {
  1029. name: "Matching secrets found",
  1030. ref: esv1beta1.ExternalSecretFind{
  1031. Name: &esv1beta1.FindName{
  1032. RegExp: secretName,
  1033. },
  1034. Path: ptr.To(secretPath),
  1035. },
  1036. secretName: secretName,
  1037. secretVersion: secretVersion,
  1038. secretValue: secretValue,
  1039. batchGetSecretValueWithContextFn: func(_ aws.Context, input *awssm.BatchGetSecretValueInput, _ ...request.Option) (*awssm.BatchGetSecretValueOutput, error) {
  1040. assert.Len(t, input.Filters, 1)
  1041. assert.Equal(t, "name", *input.Filters[0].Key)
  1042. assert.Equal(t, secretPath, *input.Filters[0].Values[0])
  1043. return &awssm.BatchGetSecretValueOutput{
  1044. SecretValues: []*awssm.SecretValueEntry{
  1045. {
  1046. Name: ptr.To(secretName),
  1047. VersionStages: []*string{ptr.To(secretVersion)},
  1048. SecretBinary: []byte(secretValue),
  1049. },
  1050. },
  1051. }, nil
  1052. },
  1053. expectedData: map[string][]byte{
  1054. secretName: []byte(secretValue),
  1055. },
  1056. expectedError: "",
  1057. },
  1058. {
  1059. name: "Error occurred while fetching secret value",
  1060. ref: esv1beta1.ExternalSecretFind{
  1061. Name: &esv1beta1.FindName{
  1062. RegExp: secretName,
  1063. },
  1064. Path: ptr.To(secretPath),
  1065. },
  1066. secretName: secretName,
  1067. secretVersion: secretVersion,
  1068. secretValue: secretValue,
  1069. batchGetSecretValueWithContextFn: func(aws.Context, *awssm.BatchGetSecretValueInput, ...request.Option) (*awssm.BatchGetSecretValueOutput, error) {
  1070. return &awssm.BatchGetSecretValueOutput{
  1071. SecretValues: []*awssm.SecretValueEntry{
  1072. {
  1073. Name: ptr.To(secretName),
  1074. },
  1075. },
  1076. }, errBoom
  1077. },
  1078. expectedData: nil,
  1079. expectedError: errBoom.Error(),
  1080. },
  1081. {
  1082. name: "regexp: error occurred while listing secrets",
  1083. ref: esv1beta1.ExternalSecretFind{
  1084. Name: &esv1beta1.FindName{
  1085. RegExp: secretName,
  1086. },
  1087. },
  1088. listSecretsFn: func(ctx context.Context, input *awssm.ListSecretsInput, opts ...request.Option) (*awssm.ListSecretsOutput, error) {
  1089. return nil, errBoom
  1090. },
  1091. expectedData: nil,
  1092. expectedError: errBoom.Error(),
  1093. },
  1094. {
  1095. name: "regep: no matching secrets found",
  1096. ref: esv1beta1.ExternalSecretFind{
  1097. Name: &esv1beta1.FindName{
  1098. RegExp: secretName,
  1099. },
  1100. },
  1101. listSecretsFn: func(ctx context.Context, input *awssm.ListSecretsInput, opts ...request.Option) (*awssm.ListSecretsOutput, error) {
  1102. return &awssm.ListSecretsOutput{
  1103. SecretList: []*awssm.SecretListEntry{
  1104. {
  1105. Name: ptr.To("other-secret"),
  1106. },
  1107. },
  1108. }, nil
  1109. },
  1110. batchGetSecretValueWithContextFn: func(aws.Context, *awssm.BatchGetSecretValueInput, ...request.Option) (*awssm.BatchGetSecretValueOutput, error) {
  1111. return &awssm.BatchGetSecretValueOutput{
  1112. SecretValues: []*awssm.SecretValueEntry{
  1113. {
  1114. Name: ptr.To("other-secret"),
  1115. },
  1116. },
  1117. }, nil
  1118. },
  1119. expectedData: make(map[string][]byte),
  1120. expectedError: "",
  1121. },
  1122. {
  1123. name: "invalid regexp",
  1124. ref: esv1beta1.ExternalSecretFind{
  1125. Name: &esv1beta1.FindName{
  1126. RegExp: "[",
  1127. },
  1128. },
  1129. expectedData: nil,
  1130. expectedError: "could not compile find.name.regexp [[]: error parsing regexp: missing closing ]: `[`",
  1131. },
  1132. {
  1133. name: "tags: Matching secrets found",
  1134. ref: esv1beta1.ExternalSecretFind{
  1135. Tags: secretTags,
  1136. },
  1137. secretName: secretName,
  1138. secretVersion: secretVersion,
  1139. secretValue: secretValue,
  1140. batchGetSecretValueWithContextFn: func(_ aws.Context, input *awssm.BatchGetSecretValueInput, _ ...request.Option) (*awssm.BatchGetSecretValueOutput, error) {
  1141. assert.Len(t, input.Filters, 2)
  1142. assert.Equal(t, "tag-key", *input.Filters[0].Key)
  1143. assert.Equal(t, "foo", *input.Filters[0].Values[0])
  1144. assert.Equal(t, "tag-value", *input.Filters[1].Key)
  1145. assert.Equal(t, "bar", *input.Filters[1].Values[0])
  1146. return &awssm.BatchGetSecretValueOutput{
  1147. SecretValues: []*awssm.SecretValueEntry{
  1148. {
  1149. Name: ptr.To(secretName),
  1150. VersionStages: []*string{ptr.To(secretVersion)},
  1151. SecretBinary: []byte(secretValue),
  1152. },
  1153. },
  1154. }, nil
  1155. },
  1156. expectedData: map[string][]byte{
  1157. secretName: []byte(secretValue),
  1158. },
  1159. expectedError: "",
  1160. },
  1161. {
  1162. name: "tags: error occurred while fetching secret value",
  1163. ref: esv1beta1.ExternalSecretFind{
  1164. Tags: secretTags,
  1165. },
  1166. secretName: secretName,
  1167. secretVersion: secretVersion,
  1168. secretValue: secretValue,
  1169. batchGetSecretValueWithContextFn: func(aws.Context, *awssm.BatchGetSecretValueInput, ...request.Option) (*awssm.BatchGetSecretValueOutput, error) {
  1170. return &awssm.BatchGetSecretValueOutput{
  1171. SecretValues: []*awssm.SecretValueEntry{
  1172. {
  1173. Name: ptr.To(secretName),
  1174. VersionStages: []*string{ptr.To(secretVersion)},
  1175. SecretBinary: []byte(secretValue),
  1176. },
  1177. },
  1178. }, errBoom
  1179. },
  1180. expectedData: nil,
  1181. expectedError: errBoom.Error(),
  1182. },
  1183. {
  1184. name: "tags: error occurred while listing secrets",
  1185. ref: esv1beta1.ExternalSecretFind{
  1186. Tags: secretTags,
  1187. },
  1188. batchGetSecretValueWithContextFn: func(aws.Context, *awssm.BatchGetSecretValueInput, ...request.Option) (*awssm.BatchGetSecretValueOutput, error) {
  1189. return nil, errBoom
  1190. },
  1191. expectedData: nil,
  1192. expectedError: errBoom.Error(),
  1193. },
  1194. }
  1195. for _, tc := range testCases {
  1196. t.Run(tc.name, func(t *testing.T) {
  1197. fc := fakesm.NewClient()
  1198. fc.BatchGetSecretValueWithContextFn = tc.batchGetSecretValueWithContextFn
  1199. fc.ListSecretsFn = tc.listSecretsFn
  1200. sm := SecretsManager{
  1201. client: fc,
  1202. cache: make(map[string]*awssm.GetSecretValueOutput),
  1203. }
  1204. data, err := sm.GetAllSecrets(ctx, tc.ref)
  1205. if err != nil && err.Error() != tc.expectedError {
  1206. t.Errorf("unexpected error: got %v, want %v", err, tc.expectedError)
  1207. }
  1208. if !reflect.DeepEqual(data, tc.expectedData) {
  1209. t.Errorf("unexpected data: got %v, want %v", data, tc.expectedData)
  1210. }
  1211. })
  1212. }
  1213. }
  1214. func TestSecretsManagerValidate(t *testing.T) {
  1215. type fields struct {
  1216. sess *session.Session
  1217. referentAuth bool
  1218. }
  1219. validSession, _ := session.NewSession(aws.NewConfig().WithCredentials(credentials.NewStaticCredentials("fake", "fake", "fake")))
  1220. invalidSession, _ := session.NewSession(aws.NewConfig().WithCredentials(credentials.NewCredentials(&FakeCredProvider{
  1221. retrieveFunc: func() (credentials.Value, error) {
  1222. return credentials.Value{}, errors.New("invalid credentials")
  1223. },
  1224. })))
  1225. tests := []struct {
  1226. name string
  1227. fields fields
  1228. want esv1beta1.ValidationResult
  1229. wantErr bool
  1230. }{
  1231. {
  1232. name: "ReferentAuth should always return unknown",
  1233. fields: fields{
  1234. referentAuth: true,
  1235. },
  1236. want: esv1beta1.ValidationResultUnknown,
  1237. },
  1238. {
  1239. name: "Valid credentials should return ready",
  1240. fields: fields{
  1241. sess: validSession,
  1242. },
  1243. want: esv1beta1.ValidationResultReady,
  1244. },
  1245. {
  1246. name: "Invalid credentials should return error",
  1247. fields: fields{
  1248. sess: invalidSession,
  1249. },
  1250. want: esv1beta1.ValidationResultError,
  1251. wantErr: true,
  1252. },
  1253. }
  1254. for _, tt := range tests {
  1255. t.Run(tt.name, func(t *testing.T) {
  1256. sm := &SecretsManager{
  1257. sess: tt.fields.sess,
  1258. referentAuth: tt.fields.referentAuth,
  1259. }
  1260. got, err := sm.Validate()
  1261. if (err != nil) != tt.wantErr {
  1262. t.Errorf("SecretsManager.Validate() error = %v, wantErr %v", err, tt.wantErr)
  1263. return
  1264. }
  1265. if !reflect.DeepEqual(got, tt.want) {
  1266. t.Errorf("SecretsManager.Validate() = %v, want %v", got, tt.want)
  1267. }
  1268. })
  1269. }
  1270. }
  1271. func TestSecretExists(t *testing.T) {
  1272. arn := "arn:aws:secretsmanager:us-east-1:702902267788:secret:foo-bar5-Robbgh"
  1273. defaultVersion := "00000000-0000-0000-0000-000000000002"
  1274. secretValueOutput := &awssm.GetSecretValueOutput{
  1275. ARN: &arn,
  1276. VersionId: &defaultVersion,
  1277. }
  1278. blankSecretValueOutput := &awssm.GetSecretValueOutput{}
  1279. getSecretCorrectErr := awssm.ResourceNotFoundException{}
  1280. getSecretWrongErr := awssm.InvalidRequestException{}
  1281. pushSecretDataWithoutProperty := fake.PushSecretData{SecretKey: "fake-secret-key", RemoteKey: fakeKey, Property: ""}
  1282. type args struct {
  1283. store *esv1beta1.AWSProvider
  1284. client fakesm.Client
  1285. pushSecretData fake.PushSecretData
  1286. }
  1287. type want struct {
  1288. err error
  1289. wantError bool
  1290. }
  1291. tests := map[string]struct {
  1292. args args
  1293. want want
  1294. }{
  1295. "SecretExistsReturnsTrueForExistingSecret": {
  1296. args: args{
  1297. store: makeValidSecretStore().Spec.Provider.AWS,
  1298. client: fakesm.Client{
  1299. GetSecretValueWithContextFn: fakesm.NewGetSecretValueWithContextFn(secretValueOutput, nil),
  1300. },
  1301. pushSecretData: pushSecretDataWithoutProperty,
  1302. },
  1303. want: want{
  1304. err: nil,
  1305. wantError: true,
  1306. },
  1307. },
  1308. "SecretExistsReturnsFalseForNonExistingSecret": {
  1309. args: args{
  1310. store: makeValidSecretStore().Spec.Provider.AWS,
  1311. client: fakesm.Client{
  1312. GetSecretValueWithContextFn: fakesm.NewGetSecretValueWithContextFn(blankSecretValueOutput, &getSecretCorrectErr),
  1313. },
  1314. pushSecretData: pushSecretDataWithoutProperty,
  1315. },
  1316. want: want{
  1317. err: nil,
  1318. wantError: false,
  1319. },
  1320. },
  1321. "SecretExistsReturnsFalseForErroredSecret": {
  1322. args: args{
  1323. store: makeValidSecretStore().Spec.Provider.AWS,
  1324. client: fakesm.Client{
  1325. GetSecretValueWithContextFn: fakesm.NewGetSecretValueWithContextFn(blankSecretValueOutput, &getSecretWrongErr),
  1326. },
  1327. pushSecretData: pushSecretDataWithoutProperty,
  1328. },
  1329. want: want{
  1330. err: &getSecretWrongErr,
  1331. wantError: false,
  1332. },
  1333. },
  1334. }
  1335. for name, tc := range tests {
  1336. t.Run(name, func(t *testing.T) {
  1337. sm := &SecretsManager{
  1338. client: &tc.args.client,
  1339. }
  1340. got, err := sm.SecretExists(context.Background(), tc.args.pushSecretData)
  1341. assert.Equal(
  1342. t,
  1343. tc.want,
  1344. want{
  1345. err: err,
  1346. wantError: got,
  1347. })
  1348. })
  1349. }
  1350. }
  1351. // FakeCredProvider implements the AWS credentials.Provider interface
  1352. // It is used to inject an error into the AWS session to cause a
  1353. // validation error.
  1354. type FakeCredProvider struct {
  1355. retrieveFunc func() (credentials.Value, error)
  1356. }
  1357. func (f *FakeCredProvider) Retrieve() (credentials.Value, error) {
  1358. return f.retrieveFunc()
  1359. }
  1360. func (f *FakeCredProvider) IsExpired() bool {
  1361. return true
  1362. }