secretsmanager_test.go 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947
  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. "encoding/json"
  16. "errors"
  17. "fmt"
  18. "reflect"
  19. "strings"
  20. "testing"
  21. "time"
  22. "github.com/aws/aws-sdk-go-v2/aws"
  23. "github.com/aws/aws-sdk-go-v2/credentials"
  24. awssm "github.com/aws/aws-sdk-go-v2/service/secretsmanager"
  25. "github.com/aws/aws-sdk-go-v2/service/secretsmanager/types"
  26. "github.com/external-secrets/external-secrets/pkg/utils/metadata"
  27. "github.com/google/go-cmp/cmp"
  28. "github.com/stretchr/testify/assert"
  29. "github.com/stretchr/testify/require"
  30. corev1 "k8s.io/api/core/v1"
  31. apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
  32. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  33. "k8s.io/utils/ptr"
  34. esv1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1"
  35. fakesm "github.com/external-secrets/external-secrets/pkg/provider/aws/secretsmanager/fake"
  36. "github.com/external-secrets/external-secrets/pkg/provider/aws/util"
  37. "github.com/external-secrets/external-secrets/pkg/provider/testing/fake"
  38. )
  39. type secretsManagerTestCase struct {
  40. fakeClient *fakesm.Client
  41. apiInput *awssm.GetSecretValueInput
  42. apiOutput *awssm.GetSecretValueOutput
  43. remoteRef *esv1.ExternalSecretDataRemoteRef
  44. apiErr error
  45. expectError string
  46. expectedSecret string
  47. // for testing secretmap
  48. expectedData map[string][]byte
  49. // for testing caching
  50. expectedCounter *int
  51. prefix string
  52. }
  53. const unexpectedErrorString = "[%d] unexpected error: %s, expected: '%s'"
  54. const (
  55. tagname1 = "tagname1"
  56. tagvalue1 = "tagvalue1"
  57. tagname2 = "tagname2"
  58. tagvalue2 = "tagvalue2"
  59. fakeKey = "fake-key"
  60. )
  61. func makeValidSecretsManagerTestCase() *secretsManagerTestCase {
  62. smtc := secretsManagerTestCase{
  63. fakeClient: fakesm.NewClient(),
  64. apiInput: makeValidAPIInput(),
  65. remoteRef: makeValidRemoteRef(),
  66. apiOutput: makeValidAPIOutput(),
  67. apiErr: nil,
  68. expectError: "",
  69. expectedSecret: "",
  70. expectedData: map[string][]byte{},
  71. }
  72. smtc.fakeClient.WithValue(smtc.apiInput, smtc.apiOutput, smtc.apiErr)
  73. return &smtc
  74. }
  75. func makeValidRemoteRef() *esv1.ExternalSecretDataRemoteRef {
  76. return &esv1.ExternalSecretDataRemoteRef{
  77. Key: "/baz",
  78. Version: "AWSCURRENT",
  79. }
  80. }
  81. func makeValidAPIInput() *awssm.GetSecretValueInput {
  82. return &awssm.GetSecretValueInput{
  83. SecretId: aws.String("/baz"),
  84. VersionStage: aws.String("AWSCURRENT"),
  85. }
  86. }
  87. func makeValidAPIOutput() *awssm.GetSecretValueOutput {
  88. return &awssm.GetSecretValueOutput{
  89. SecretString: aws.String(""),
  90. }
  91. }
  92. func makeValidSecretsManagerTestCaseCustom(tweaks ...func(smtc *secretsManagerTestCase)) *secretsManagerTestCase {
  93. smtc := makeValidSecretsManagerTestCase()
  94. for _, fn := range tweaks {
  95. fn(smtc)
  96. }
  97. smtc.fakeClient.WithValue(smtc.apiInput, smtc.apiOutput, smtc.apiErr)
  98. return smtc
  99. }
  100. // This case can be shared by both GetSecret and GetSecretMap tests.
  101. // bad case: set apiErr.
  102. var setAPIErr = func(smtc *secretsManagerTestCase) {
  103. smtc.apiErr = errors.New("oh no")
  104. smtc.expectError = "oh no"
  105. }
  106. func TestSecretsManagerResolver(t *testing.T) {
  107. endpointEnvKey := SecretsManagerEndpointEnv
  108. endpointURL := "http://sm.foo"
  109. t.Setenv(endpointEnvKey, endpointURL)
  110. f, err := customEndpointResolver{}.ResolveEndpoint(context.Background(), awssm.EndpointParameters{})
  111. assert.Nil(t, err)
  112. assert.Equal(t, endpointURL, f.URI.String())
  113. }
  114. // test the sm<->aws interface
  115. // make sure correct values are passed and errors are handled accordingly.
  116. func TestSecretsManagerGetSecret(t *testing.T) {
  117. // good case: default version is set
  118. // key is passed in, output is sent back
  119. setSecretString := func(smtc *secretsManagerTestCase) {
  120. smtc.apiOutput.SecretString = aws.String("testtesttest")
  121. smtc.expectedSecret = "testtesttest"
  122. }
  123. // good case: key is passed in with prefix
  124. setSecretStringWithPrefix := func(smtc *secretsManagerTestCase) {
  125. smtc.remoteRef.Key = "secret-key"
  126. smtc.apiInput = &awssm.GetSecretValueInput{
  127. SecretId: aws.String("my-prefix/secret-key"),
  128. VersionStage: aws.String("AWSCURRENT"),
  129. }
  130. smtc.prefix = "my-prefix/"
  131. }
  132. // good case: extract property
  133. // Testing that the property exists in the SecretString
  134. setRemoteRefPropertyExistsInKey := func(smtc *secretsManagerTestCase) {
  135. smtc.remoteRef.Property = "/shmoo"
  136. smtc.apiOutput.SecretString = aws.String(`{"/shmoo": "bang"}`)
  137. smtc.expectedSecret = "bang"
  138. }
  139. // bad case: missing property
  140. setRemoteRefMissingProperty := func(smtc *secretsManagerTestCase) {
  141. smtc.remoteRef.Property = "INVALPROP"
  142. smtc.expectError = "key INVALPROP does not exist in secret"
  143. }
  144. // bad case: extract property failure due to invalid json
  145. setRemoteRefMissingPropertyInvalidJSON := func(smtc *secretsManagerTestCase) {
  146. smtc.remoteRef.Property = "INVALPROP"
  147. smtc.apiOutput.SecretString = aws.String(`------`)
  148. smtc.expectError = "key INVALPROP does not exist in secret"
  149. }
  150. // good case: set .SecretString to nil but set binary with value
  151. setSecretBinaryNotSecretString := func(smtc *secretsManagerTestCase) {
  152. smtc.apiOutput.SecretBinary = []byte("yesplease")
  153. // needs to be set as nil, empty quotes ("") is considered existing
  154. smtc.apiOutput.SecretString = nil
  155. smtc.expectedSecret = "yesplease"
  156. }
  157. // bad case: both .SecretString and .SecretBinary are nil
  158. setSecretBinaryAndSecretStringToNil := func(smtc *secretsManagerTestCase) {
  159. smtc.apiOutput.SecretBinary = nil
  160. smtc.apiOutput.SecretString = nil
  161. smtc.expectError = "no secret string nor binary for key"
  162. }
  163. // good case: secretOut.SecretBinary JSON parsing
  164. setNestedSecretValueJSONParsing := func(smtc *secretsManagerTestCase) {
  165. smtc.apiOutput.SecretString = nil
  166. smtc.apiOutput.SecretBinary = []byte(`{"foobar":{"baz":"nestedval"}}`)
  167. smtc.remoteRef.Property = "foobar.baz"
  168. smtc.expectedSecret = "nestedval"
  169. }
  170. // good case: secretOut.SecretBinary no JSON parsing if name on key
  171. setSecretValueWithDot := func(smtc *secretsManagerTestCase) {
  172. smtc.apiOutput.SecretString = nil
  173. smtc.apiOutput.SecretBinary = []byte(`{"foobar.baz":"nestedval"}`)
  174. smtc.remoteRef.Property = "foobar.baz"
  175. smtc.expectedSecret = "nestedval"
  176. }
  177. // good case: custom version stage set
  178. setCustomVersionStage := func(smtc *secretsManagerTestCase) {
  179. smtc.apiInput.VersionStage = aws.String("1234")
  180. smtc.remoteRef.Version = "1234"
  181. smtc.apiOutput.SecretString = aws.String("FOOBA!")
  182. smtc.expectedSecret = "FOOBA!"
  183. }
  184. // good case: custom version id set
  185. setCustomVersionID := func(smtc *secretsManagerTestCase) {
  186. smtc.apiInput.VersionStage = nil
  187. smtc.apiInput.VersionId = aws.String("1234-5678")
  188. smtc.remoteRef.Version = "uuid/1234-5678"
  189. smtc.apiOutput.SecretString = aws.String("myvalue")
  190. smtc.expectedSecret = "myvalue"
  191. }
  192. fetchMetadata := func(smtc *secretsManagerTestCase) {
  193. smtc.remoteRef.MetadataPolicy = esv1.ExternalSecretMetadataPolicyFetch
  194. describeSecretOutput := &awssm.DescribeSecretOutput{
  195. Tags: getTagSlice(),
  196. }
  197. smtc.fakeClient.DescribeSecretFn = fakesm.NewDescribeSecretFn(describeSecretOutput, nil)
  198. jsonTags, _ := util.SecretTagsToJSONString(getTagSlice())
  199. smtc.apiOutput.SecretString = &jsonTags
  200. smtc.expectedSecret = jsonTags
  201. }
  202. fetchMetadataProperty := func(smtc *secretsManagerTestCase) {
  203. smtc.remoteRef.MetadataPolicy = esv1.ExternalSecretMetadataPolicyFetch
  204. describeSecretOutput := &awssm.DescribeSecretOutput{
  205. Tags: getTagSlice(),
  206. }
  207. smtc.fakeClient.DescribeSecretFn = fakesm.NewDescribeSecretFn(describeSecretOutput, nil)
  208. smtc.remoteRef.Property = tagname2
  209. jsonTags, _ := util.SecretTagsToJSONString(getTagSlice())
  210. smtc.apiOutput.SecretString = &jsonTags
  211. smtc.expectedSecret = tagvalue2
  212. }
  213. failMetadataWrongProperty := func(smtc *secretsManagerTestCase) {
  214. smtc.remoteRef.MetadataPolicy = esv1.ExternalSecretMetadataPolicyFetch
  215. describeSecretOutput := &awssm.DescribeSecretOutput{
  216. Tags: getTagSlice(),
  217. }
  218. smtc.fakeClient.DescribeSecretFn = fakesm.NewDescribeSecretFn(describeSecretOutput, nil)
  219. smtc.remoteRef.Property = "fail"
  220. jsonTags, _ := util.SecretTagsToJSONString(getTagSlice())
  221. smtc.apiOutput.SecretString = &jsonTags
  222. smtc.expectError = "key fail does not exist in secret /baz"
  223. }
  224. successCases := []*secretsManagerTestCase{
  225. makeValidSecretsManagerTestCase(),
  226. makeValidSecretsManagerTestCaseCustom(setSecretString),
  227. makeValidSecretsManagerTestCaseCustom(setSecretStringWithPrefix),
  228. makeValidSecretsManagerTestCaseCustom(setRemoteRefPropertyExistsInKey),
  229. makeValidSecretsManagerTestCaseCustom(setRemoteRefMissingProperty),
  230. makeValidSecretsManagerTestCaseCustom(setRemoteRefMissingPropertyInvalidJSON),
  231. makeValidSecretsManagerTestCaseCustom(setSecretBinaryNotSecretString),
  232. makeValidSecretsManagerTestCaseCustom(setSecretBinaryAndSecretStringToNil),
  233. makeValidSecretsManagerTestCaseCustom(setNestedSecretValueJSONParsing),
  234. makeValidSecretsManagerTestCaseCustom(setSecretValueWithDot),
  235. makeValidSecretsManagerTestCaseCustom(setCustomVersionStage),
  236. makeValidSecretsManagerTestCaseCustom(setCustomVersionID),
  237. makeValidSecretsManagerTestCaseCustom(setAPIErr),
  238. makeValidSecretsManagerTestCaseCustom(fetchMetadata),
  239. makeValidSecretsManagerTestCaseCustom(fetchMetadataProperty),
  240. makeValidSecretsManagerTestCaseCustom(failMetadataWrongProperty),
  241. }
  242. for k, v := range successCases {
  243. sm := SecretsManager{
  244. cache: make(map[string]*awssm.GetSecretValueOutput),
  245. client: v.fakeClient,
  246. prefix: v.prefix,
  247. }
  248. out, err := sm.GetSecret(context.Background(), *v.remoteRef)
  249. if !ErrorContains(err, v.expectError) {
  250. t.Errorf(unexpectedErrorString, k, err.Error(), v.expectError)
  251. }
  252. if err == nil && string(out) != v.expectedSecret {
  253. t.Errorf("[%d] unexpected secret: expected %s, got %s", k, v.expectedSecret, string(out))
  254. }
  255. }
  256. }
  257. func TestCaching(t *testing.T) {
  258. fakeClient := fakesm.NewClient()
  259. // good case: first call, since we are using the same key, results should be cached and the counter should not go
  260. // over 1
  261. firstCall := func(smtc *secretsManagerTestCase) {
  262. smtc.apiOutput.SecretString = aws.String(`{"foo":"bar", "bar":"vodka"}`)
  263. smtc.remoteRef.Property = "foo"
  264. smtc.expectedSecret = "bar"
  265. smtc.expectedCounter = aws.Int(1)
  266. smtc.fakeClient = fakeClient
  267. }
  268. secondCall := func(smtc *secretsManagerTestCase) {
  269. smtc.apiOutput.SecretString = aws.String(`{"foo":"bar", "bar":"vodka"}`)
  270. smtc.remoteRef.Property = "bar"
  271. smtc.expectedSecret = "vodka"
  272. smtc.expectedCounter = aws.Int(1)
  273. smtc.fakeClient = fakeClient
  274. }
  275. notCachedCall := func(smtc *secretsManagerTestCase) {
  276. smtc.apiOutput.SecretString = aws.String(`{"sheldon":"bazinga", "bar":"foo"}`)
  277. smtc.remoteRef.Property = "sheldon"
  278. smtc.expectedSecret = "bazinga"
  279. smtc.expectedCounter = aws.Int(2)
  280. smtc.fakeClient = fakeClient
  281. smtc.apiInput.SecretId = aws.String("xyz")
  282. smtc.remoteRef.Key = "xyz" // it should reset the cache since the key is different
  283. }
  284. cachedCases := []*secretsManagerTestCase{
  285. makeValidSecretsManagerTestCaseCustom(firstCall),
  286. makeValidSecretsManagerTestCaseCustom(firstCall),
  287. makeValidSecretsManagerTestCaseCustom(secondCall),
  288. makeValidSecretsManagerTestCaseCustom(notCachedCall),
  289. }
  290. sm := SecretsManager{
  291. cache: make(map[string]*awssm.GetSecretValueOutput),
  292. }
  293. for k, v := range cachedCases {
  294. sm.client = v.fakeClient
  295. out, err := sm.GetSecret(context.Background(), *v.remoteRef)
  296. if !ErrorContains(err, v.expectError) {
  297. t.Errorf(unexpectedErrorString, k, err.Error(), v.expectError)
  298. }
  299. if err == nil && string(out) != v.expectedSecret {
  300. t.Errorf("[%d] unexpected secret: expected %s, got %s", k, v.expectedSecret, string(out))
  301. }
  302. if v.expectedCounter != nil && v.fakeClient.ExecutionCounter != *v.expectedCounter {
  303. t.Errorf("[%d] unexpected counter value: expected %d, got %d", k, v.expectedCounter, v.fakeClient.ExecutionCounter)
  304. }
  305. }
  306. }
  307. func TestGetSecretMap(t *testing.T) {
  308. // good case: default version & deserialization
  309. setDeserialization := func(smtc *secretsManagerTestCase) {
  310. smtc.apiOutput.SecretString = aws.String(`{"foo":"bar"}`)
  311. smtc.expectedData["foo"] = []byte("bar")
  312. }
  313. // good case: nested json
  314. setNestedJSON := func(smtc *secretsManagerTestCase) {
  315. smtc.apiOutput.SecretString = aws.String(`{"foobar":{"baz":"nestedval"}}`)
  316. smtc.expectedData["foobar"] = []byte("{\"baz\":\"nestedval\"}")
  317. }
  318. // good case: caching
  319. cachedMap := func(smtc *secretsManagerTestCase) {
  320. smtc.apiOutput.SecretString = aws.String(`{"foo":"bar", "plus": "one"}`)
  321. smtc.expectedData["foo"] = []byte("bar")
  322. smtc.expectedData["plus"] = []byte("one")
  323. smtc.expectedCounter = aws.Int(1)
  324. }
  325. // bad case: invalid json
  326. setInvalidJSON := func(smtc *secretsManagerTestCase) {
  327. smtc.apiOutput.SecretString = aws.String(`-----------------`)
  328. smtc.expectError = "unable to unmarshal secret"
  329. }
  330. successCases := []*secretsManagerTestCase{
  331. makeValidSecretsManagerTestCaseCustom(setDeserialization),
  332. makeValidSecretsManagerTestCaseCustom(setNestedJSON),
  333. makeValidSecretsManagerTestCaseCustom(setAPIErr),
  334. makeValidSecretsManagerTestCaseCustom(setInvalidJSON),
  335. makeValidSecretsManagerTestCaseCustom(cachedMap),
  336. }
  337. for k, v := range successCases {
  338. sm := SecretsManager{
  339. cache: make(map[string]*awssm.GetSecretValueOutput),
  340. client: v.fakeClient,
  341. }
  342. out, err := sm.GetSecretMap(context.Background(), *v.remoteRef)
  343. if !ErrorContains(err, v.expectError) {
  344. t.Errorf(unexpectedErrorString, k, err.Error(), v.expectError)
  345. }
  346. if err == nil && !cmp.Equal(out, v.expectedData) {
  347. t.Errorf("[%d] unexpected secret data: expected %#v, got %#v", k, v.expectedData, out)
  348. }
  349. if v.expectedCounter != nil && v.fakeClient.ExecutionCounter != *v.expectedCounter {
  350. t.Errorf("[%d] unexpected counter value: expected %d, got %d", k, v.expectedCounter, v.fakeClient.ExecutionCounter)
  351. }
  352. }
  353. }
  354. func ErrorContains(out error, want string) bool {
  355. if out == nil {
  356. return want == ""
  357. }
  358. if want == "" {
  359. return false
  360. }
  361. return strings.Contains(out.Error(), want)
  362. }
  363. func TestSetSecret(t *testing.T) {
  364. managedBy := managedBy
  365. notManagedBy := "not-managed-by"
  366. secretKey := "fake-secret-key"
  367. secretValue := []byte("fake-value")
  368. fakeSecret := &corev1.Secret{
  369. Data: map[string][]byte{
  370. secretKey: secretValue,
  371. },
  372. }
  373. externalSecrets := externalSecrets
  374. noPermission := errors.New("no permission")
  375. arn := "arn:aws:secretsmanager:us-east-1:702902267788:secret:foo-bar5-Robbgh"
  376. getSecretCorrectErr := types.ResourceNotFoundException{}
  377. getSecretWrongErr := types.InvalidRequestException{}
  378. secretOutput := &awssm.CreateSecretOutput{
  379. ARN: &arn,
  380. }
  381. externalSecretsTag := []types.Tag{
  382. {
  383. Key: &managedBy,
  384. Value: &externalSecrets,
  385. },
  386. {
  387. Key: ptr.To("taname1"),
  388. Value: ptr.To("tagvalue1"),
  389. },
  390. }
  391. externalSecretsTagFaulty := []types.Tag{
  392. {
  393. Key: &notManagedBy,
  394. Value: &externalSecrets,
  395. },
  396. }
  397. tagSecretOutput := &awssm.DescribeSecretOutput{
  398. ARN: &arn,
  399. Tags: externalSecretsTag,
  400. }
  401. tagSecretOutputFaulty := &awssm.DescribeSecretOutput{
  402. ARN: &arn,
  403. Tags: externalSecretsTagFaulty,
  404. }
  405. initialVersion := "00000000-0000-0000-0000-000000000001"
  406. defaultVersion := "00000000-0000-0000-0000-000000000002"
  407. defaultUpdatedVersion := "00000000-0000-0000-0000-000000000003"
  408. randomUUIDVersion := "c2812e8d-84ce-4858-abec-7163d8ab312b"
  409. randomUUIDVersionIncremented := "c2812e8d-84ce-4858-abec-7163d8ab312c"
  410. unparsableVersion := "IAM UNPARSABLE"
  411. secretValueOutput := &awssm.GetSecretValueOutput{
  412. ARN: &arn,
  413. VersionId: &defaultVersion,
  414. }
  415. secretValueOutput2 := &awssm.GetSecretValueOutput{
  416. ARN: &arn,
  417. SecretBinary: secretValue,
  418. VersionId: &defaultVersion,
  419. }
  420. type params struct {
  421. s string
  422. b []byte
  423. version *string
  424. }
  425. secretValueOutputFrom := func(params params) *awssm.GetSecretValueOutput {
  426. var version *string
  427. if params.version == nil {
  428. version = &defaultVersion
  429. } else {
  430. version = params.version
  431. }
  432. return &awssm.GetSecretValueOutput{
  433. ARN: &arn,
  434. SecretString: &params.s,
  435. SecretBinary: params.b,
  436. VersionId: version,
  437. }
  438. }
  439. blankSecretValueOutput := &awssm.GetSecretValueOutput{}
  440. putSecretOutput := &awssm.PutSecretValueOutput{
  441. ARN: &arn,
  442. }
  443. pushSecretDataWithoutProperty := fake.PushSecretData{SecretKey: secretKey, RemoteKey: fakeKey, Property: ""}
  444. pushSecretDataWithoutSecretKey := fake.PushSecretData{RemoteKey: fakeKey, Property: ""}
  445. pushSecretDataWithMetadata := fake.PushSecretData{SecretKey: secretKey, RemoteKey: fakeKey, Property: "", Metadata: &apiextensionsv1.JSON{
  446. Raw: []byte(`{
  447. "apiVersion": "kubernetes.external-secrets.io/v1alpha1",
  448. "kind": "PushSecretMetadata",
  449. "spec": {
  450. "secretPushFormat": "string"
  451. }
  452. }`)}}
  453. pushSecretDataWithProperty := fake.PushSecretData{SecretKey: secretKey, RemoteKey: fakeKey, Property: "other-fake-property"}
  454. type args struct {
  455. store *esv1.AWSProvider
  456. client fakesm.Client
  457. pushSecretData fake.PushSecretData
  458. }
  459. type want struct {
  460. err error
  461. }
  462. tests := map[string]struct {
  463. reason string
  464. args args
  465. want want
  466. }{
  467. "SetSecretSucceedsWithExistingSecret": {
  468. reason: "a secret can be pushed to aws secrets manager when it already exists",
  469. args: args{
  470. store: makeValidSecretStore().Spec.Provider.AWS,
  471. client: fakesm.Client{
  472. GetSecretValueFn: fakesm.NewGetSecretValueFn(secretValueOutput, nil),
  473. CreateSecretFn: fakesm.NewCreateSecretFn(secretOutput, nil),
  474. PutSecretValueFn: fakesm.NewPutSecretValueFn(putSecretOutput, nil),
  475. DescribeSecretFn: fakesm.NewDescribeSecretFn(tagSecretOutput, nil),
  476. TagResourceFn: fakesm.NewTagResourceFn(&awssm.TagResourceOutput{}, nil),
  477. UntagResourceFn: fakesm.NewUntagResourceFn(&awssm.UntagResourceOutput{}, nil),
  478. },
  479. pushSecretData: pushSecretDataWithoutProperty,
  480. },
  481. want: want{
  482. err: nil,
  483. },
  484. },
  485. "SetSecretSucceedsWithoutSecretKey": {
  486. reason: "a secret can be pushed to aws secrets manager without secret key",
  487. args: args{
  488. store: makeValidSecretStore().Spec.Provider.AWS,
  489. client: fakesm.Client{
  490. GetSecretValueFn: fakesm.NewGetSecretValueFn(secretValueOutput, nil),
  491. CreateSecretFn: fakesm.NewCreateSecretFn(secretOutput, nil),
  492. PutSecretValueFn: fakesm.NewPutSecretValueFn(putSecretOutput, nil),
  493. DescribeSecretFn: fakesm.NewDescribeSecretFn(tagSecretOutput, nil),
  494. TagResourceFn: fakesm.NewTagResourceFn(&awssm.TagResourceOutput{}, nil),
  495. UntagResourceFn: fakesm.NewUntagResourceFn(&awssm.UntagResourceOutput{}, nil),
  496. },
  497. pushSecretData: pushSecretDataWithoutSecretKey,
  498. },
  499. want: want{
  500. err: nil,
  501. },
  502. },
  503. "SetSecretSucceedsWithExistingSecretAndStringFormat": {
  504. reason: "a secret can be pushed to aws secrets manager when it already exists",
  505. args: args{
  506. store: makeValidSecretStore().Spec.Provider.AWS,
  507. client: fakesm.Client{
  508. GetSecretValueFn: fakesm.NewGetSecretValueFn(secretValueOutput, nil),
  509. CreateSecretFn: fakesm.NewCreateSecretFn(secretOutput, nil),
  510. PutSecretValueFn: fakesm.NewPutSecretValueFn(putSecretOutput, nil),
  511. DescribeSecretFn: fakesm.NewDescribeSecretFn(tagSecretOutput, nil),
  512. TagResourceFn: fakesm.NewTagResourceFn(&awssm.TagResourceOutput{}, nil),
  513. UntagResourceFn: fakesm.NewUntagResourceFn(&awssm.UntagResourceOutput{}, nil),
  514. },
  515. pushSecretData: pushSecretDataWithMetadata,
  516. },
  517. want: want{
  518. err: nil,
  519. },
  520. },
  521. "SetSecretSucceedsWithExistingSecretAndKMSKeyAndDescription": {
  522. reason: "a secret can be pushed to aws secrets manager when it already exists",
  523. args: args{
  524. store: makeValidSecretStore().Spec.Provider.AWS,
  525. client: fakesm.Client{
  526. GetSecretValueFn: fakesm.NewGetSecretValueFn(secretValueOutput, &getSecretCorrectErr),
  527. CreateSecretFn: fakesm.NewCreateSecretFn(secretOutput, nil),
  528. PutSecretValueFn: fakesm.NewPutSecretValueFn(putSecretOutput, nil),
  529. DescribeSecretFn: fakesm.NewDescribeSecretFn(tagSecretOutput, nil),
  530. },
  531. pushSecretData: fake.PushSecretData{SecretKey: secretKey, RemoteKey: fakeKey, Property: "", Metadata: &apiextensionsv1.JSON{
  532. Raw: []byte(`{
  533. "apiVersion": "kubernetes.external-secrets.io/v1alpha1",
  534. "kind": "PushSecretMetadata",
  535. "spec": {
  536. "kmsKeyID": "bb123123-b2b0-4f60-ac3a-44a13f0e6b6c",
  537. "description": "this is a description"
  538. }
  539. }`)}},
  540. },
  541. want: want{
  542. err: nil,
  543. },
  544. },
  545. "SetSecretSucceedsWithExistingSecretAndAdditionalTags": {
  546. reason: "a secret can be pushed to aws secrets manager when it already exists",
  547. args: args{
  548. store: makeValidSecretStore().Spec.Provider.AWS,
  549. client: fakesm.Client{
  550. GetSecretValueFn: fakesm.NewGetSecretValueFn(secretValueOutput, nil),
  551. CreateSecretFn: fakesm.NewCreateSecretFn(secretOutput, nil),
  552. PutSecretValueFn: fakesm.NewPutSecretValueFn(putSecretOutput, nil),
  553. DescribeSecretFn: fakesm.NewDescribeSecretFn(tagSecretOutput, nil),
  554. TagResourceFn: fakesm.NewTagResourceFn(&awssm.TagResourceOutput{}, nil),
  555. UntagResourceFn: fakesm.NewUntagResourceFn(&awssm.UntagResourceOutput{}, nil),
  556. },
  557. pushSecretData: fake.PushSecretData{SecretKey: secretKey, RemoteKey: fakeKey, Property: "", Metadata: &apiextensionsv1.JSON{
  558. Raw: []byte(`{
  559. "apiVersion": "kubernetes.external-secrets.io/v1alpha1",
  560. "kind": "PushSecretMetadata",
  561. "spec": {
  562. "tags": {"tagname12": "tagvalue1"}
  563. }
  564. }`)}},
  565. },
  566. want: want{
  567. err: nil,
  568. },
  569. },
  570. "SetSecretSucceedsWithNewSecret": {
  571. reason: "a secret can be pushed to aws secrets manager if it doesn't already exist",
  572. args: args{
  573. store: makeValidSecretStore().Spec.Provider.AWS,
  574. client: fakesm.Client{
  575. GetSecretValueFn: fakesm.NewGetSecretValueFn(blankSecretValueOutput, &getSecretCorrectErr),
  576. CreateSecretFn: fakesm.NewCreateSecretFn(secretOutput, nil),
  577. },
  578. pushSecretData: pushSecretDataWithoutProperty,
  579. },
  580. want: want{
  581. err: nil,
  582. },
  583. },
  584. "SetSecretWithPropertySucceedsWithNewSecret": {
  585. 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",
  586. args: args{
  587. store: makeValidSecretStore().Spec.Provider.AWS,
  588. client: fakesm.Client{
  589. GetSecretValueFn: fakesm.NewGetSecretValueFn(blankSecretValueOutput, &getSecretCorrectErr),
  590. CreateSecretFn: fakesm.NewCreateSecretFn(secretOutput, nil, []byte(`{"other-fake-property":"fake-value"}`)),
  591. },
  592. pushSecretData: pushSecretDataWithProperty,
  593. },
  594. want: want{
  595. err: nil,
  596. },
  597. },
  598. "SetSecretWithPropertySucceedsWithExistingSecretAndNewPropertyBinary": {
  599. 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)",
  600. args: args{
  601. store: makeValidSecretStore().Spec.Provider.AWS,
  602. client: fakesm.Client{
  603. GetSecretValueFn: fakesm.NewGetSecretValueFn(secretValueOutputFrom(params{b: []byte((`{"fake-property":"fake-value"}`))}), nil),
  604. DescribeSecretFn: fakesm.NewDescribeSecretFn(tagSecretOutput, nil),
  605. PutSecretValueFn: fakesm.NewPutSecretValueFn(putSecretOutput, nil, fakesm.ExpectedPutSecretValueInput{
  606. SecretBinary: []byte(`{"fake-property":"fake-value","other-fake-property":"fake-value"}`),
  607. Version: &defaultUpdatedVersion,
  608. }),
  609. TagResourceFn: fakesm.NewTagResourceFn(&awssm.TagResourceOutput{}, nil),
  610. UntagResourceFn: fakesm.NewUntagResourceFn(&awssm.UntagResourceOutput{}, nil),
  611. },
  612. pushSecretData: pushSecretDataWithProperty,
  613. },
  614. want: want{
  615. err: nil,
  616. },
  617. },
  618. "SetSecretWithPropertySucceedsWithExistingSecretAndRandomUUIDVersion": {
  619. 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",
  620. args: args{
  621. store: makeValidSecretStore().Spec.Provider.AWS,
  622. client: fakesm.Client{
  623. GetSecretValueFn: fakesm.NewGetSecretValueFn(secretValueOutputFrom(params{
  624. b: []byte((`{"fake-property":"fake-value"}`)),
  625. version: &randomUUIDVersion,
  626. }), nil),
  627. DescribeSecretFn: fakesm.NewDescribeSecretFn(tagSecretOutput, nil),
  628. PutSecretValueFn: fakesm.NewPutSecretValueFn(putSecretOutput, nil, fakesm.ExpectedPutSecretValueInput{
  629. SecretBinary: []byte(`{"fake-property":"fake-value","other-fake-property":"fake-value"}`),
  630. Version: &randomUUIDVersionIncremented,
  631. }),
  632. TagResourceFn: fakesm.NewTagResourceFn(&awssm.TagResourceOutput{}, nil),
  633. UntagResourceFn: fakesm.NewUntagResourceFn(&awssm.UntagResourceOutput{}, nil),
  634. },
  635. pushSecretData: pushSecretDataWithProperty,
  636. },
  637. want: want{
  638. err: nil,
  639. },
  640. },
  641. "SetSecretWithPropertySucceedsWithExistingSecretAndVersionThatCantBeParsed": {
  642. reason: "A manually set secret version doesn't have to be a UUID, we only support UUID secret versions though",
  643. args: args{
  644. store: makeValidSecretStore().Spec.Provider.AWS,
  645. client: fakesm.Client{
  646. GetSecretValueFn: fakesm.NewGetSecretValueFn(secretValueOutputFrom(params{
  647. b: []byte((`{"fake-property":"fake-value"}`)),
  648. version: &unparsableVersion,
  649. }), nil),
  650. DescribeSecretFn: fakesm.NewDescribeSecretFn(tagSecretOutput, nil),
  651. PutSecretValueFn: fakesm.NewPutSecretValueFn(putSecretOutput, nil, fakesm.ExpectedPutSecretValueInput{
  652. SecretBinary: []byte(`{"fake-property":"fake-value","other-fake-property":"fake-value"}`),
  653. Version: &initialVersion,
  654. }),
  655. },
  656. pushSecretData: pushSecretDataWithProperty,
  657. },
  658. want: want{
  659. err: fmt.Errorf("expected secret version in AWS SSM to be a UUID but got '%s'", unparsableVersion),
  660. },
  661. },
  662. "SetSecretWithPropertySucceedsWithExistingSecretAndAbsentVersion": {
  663. reason: "When a secret version is not specified, set it to 1",
  664. args: args{
  665. store: makeValidSecretStore().Spec.Provider.AWS,
  666. client: fakesm.Client{
  667. GetSecretValueFn: fakesm.NewGetSecretValueFn(&awssm.GetSecretValueOutput{
  668. ARN: &arn,
  669. SecretBinary: []byte((`{"fake-property":"fake-value"}`)),
  670. }, nil),
  671. DescribeSecretFn: fakesm.NewDescribeSecretFn(tagSecretOutput, nil),
  672. PutSecretValueFn: fakesm.NewPutSecretValueFn(putSecretOutput, nil, fakesm.ExpectedPutSecretValueInput{
  673. SecretBinary: []byte(`{"fake-property":"fake-value","other-fake-property":"fake-value"}`),
  674. Version: &initialVersion,
  675. }),
  676. TagResourceFn: fakesm.NewTagResourceFn(&awssm.TagResourceOutput{}, nil),
  677. UntagResourceFn: fakesm.NewUntagResourceFn(&awssm.UntagResourceOutput{}, nil),
  678. },
  679. pushSecretData: pushSecretDataWithProperty,
  680. },
  681. want: want{
  682. err: nil,
  683. },
  684. },
  685. "SetSecretWithPropertySucceedsWithExistingSecretAndNewPropertyString": {
  686. 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)",
  687. args: args{
  688. store: makeValidSecretStore().Spec.Provider.AWS,
  689. client: fakesm.Client{
  690. GetSecretValueFn: fakesm.NewGetSecretValueFn(secretValueOutputFrom(params{s: `{"fake-property":"fake-value"}`}), nil),
  691. DescribeSecretFn: fakesm.NewDescribeSecretFn(tagSecretOutput, nil),
  692. PutSecretValueFn: fakesm.NewPutSecretValueFn(putSecretOutput, nil, fakesm.ExpectedPutSecretValueInput{
  693. SecretBinary: []byte(`{"fake-property":"fake-value","other-fake-property":"fake-value"}`),
  694. Version: &defaultUpdatedVersion,
  695. }),
  696. TagResourceFn: fakesm.NewTagResourceFn(&awssm.TagResourceOutput{}, nil),
  697. UntagResourceFn: fakesm.NewUntagResourceFn(&awssm.UntagResourceOutput{}, nil),
  698. },
  699. pushSecretData: pushSecretDataWithProperty,
  700. },
  701. want: want{
  702. err: nil,
  703. },
  704. },
  705. "SetSecretWithPropertySucceedsWithExistingSecretAndNewPropertyWithDot": {
  706. 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)",
  707. args: args{
  708. store: makeValidSecretStore().Spec.Provider.AWS,
  709. client: fakesm.Client{
  710. GetSecretValueFn: fakesm.NewGetSecretValueFn(secretValueOutputFrom(params{s: `{"fake-property":{"fake-property":"fake-value"}}`}), nil),
  711. DescribeSecretFn: fakesm.NewDescribeSecretFn(tagSecretOutput, nil),
  712. PutSecretValueFn: fakesm.NewPutSecretValueFn(putSecretOutput, nil, fakesm.ExpectedPutSecretValueInput{
  713. SecretBinary: []byte(`{"fake-property":{"fake-property":"fake-value","other-fake-property":"fake-value"}}`),
  714. Version: &defaultUpdatedVersion,
  715. }),
  716. TagResourceFn: fakesm.NewTagResourceFn(&awssm.TagResourceOutput{}, nil),
  717. UntagResourceFn: fakesm.NewUntagResourceFn(&awssm.UntagResourceOutput{}, nil),
  718. },
  719. pushSecretData: fake.PushSecretData{SecretKey: secretKey, RemoteKey: fakeKey, Property: "fake-property.other-fake-property"},
  720. },
  721. want: want{
  722. err: nil,
  723. },
  724. },
  725. "SetSecretWithPropertyFailsExistingNonJsonSecret": {
  726. reason: "setting a pushSecretData property is only supported for json secrets",
  727. args: args{
  728. store: makeValidSecretStore().Spec.Provider.AWS,
  729. client: fakesm.Client{
  730. GetSecretValueFn: fakesm.NewGetSecretValueFn(secretValueOutputFrom(params{s: `non-json-secret`}), nil),
  731. DescribeSecretFn: fakesm.NewDescribeSecretFn(tagSecretOutput, nil),
  732. },
  733. pushSecretData: pushSecretDataWithProperty,
  734. },
  735. want: want{
  736. err: errors.New("PushSecret for aws secrets manager with a pushSecretData property requires a json secret"),
  737. },
  738. },
  739. "SetSecretCreateSecretFails": {
  740. reason: "CreateSecretWithContext returns an error if it fails",
  741. args: args{
  742. store: makeValidSecretStore().Spec.Provider.AWS,
  743. client: fakesm.Client{
  744. GetSecretValueFn: fakesm.NewGetSecretValueFn(blankSecretValueOutput, &getSecretCorrectErr),
  745. CreateSecretFn: fakesm.NewCreateSecretFn(nil, noPermission),
  746. },
  747. pushSecretData: pushSecretDataWithoutProperty,
  748. },
  749. want: want{
  750. err: noPermission,
  751. },
  752. },
  753. "SetSecretGetSecretFails": {
  754. reason: "GetSecretValueWithContext returns an error if it fails",
  755. args: args{
  756. store: makeValidSecretStore().Spec.Provider.AWS,
  757. client: fakesm.Client{
  758. GetSecretValueFn: fakesm.NewGetSecretValueFn(blankSecretValueOutput, noPermission),
  759. },
  760. pushSecretData: pushSecretDataWithoutProperty,
  761. },
  762. want: want{
  763. err: noPermission,
  764. },
  765. },
  766. "SetSecretWillNotPushSameSecret": {
  767. reason: "secret with the same value will not be pushed",
  768. args: args{
  769. store: makeValidSecretStore().Spec.Provider.AWS,
  770. client: fakesm.Client{
  771. GetSecretValueFn: fakesm.NewGetSecretValueFn(secretValueOutput2, nil),
  772. DescribeSecretFn: fakesm.NewDescribeSecretFn(tagSecretOutput, nil),
  773. },
  774. pushSecretData: pushSecretDataWithoutProperty,
  775. },
  776. want: want{
  777. err: nil,
  778. },
  779. },
  780. "SetSecretPutSecretValueFails": {
  781. reason: "PutSecretValueWithContext returns an error if it fails",
  782. args: args{
  783. store: makeValidSecretStore().Spec.Provider.AWS,
  784. client: fakesm.Client{
  785. GetSecretValueFn: fakesm.NewGetSecretValueFn(secretValueOutput, nil),
  786. PutSecretValueFn: fakesm.NewPutSecretValueFn(nil, noPermission),
  787. DescribeSecretFn: fakesm.NewDescribeSecretFn(tagSecretOutput, nil),
  788. TagResourceFn: fakesm.NewTagResourceFn(&awssm.TagResourceOutput{}, nil),
  789. UntagResourceFn: fakesm.NewUntagResourceFn(&awssm.UntagResourceOutput{}, nil),
  790. },
  791. pushSecretData: pushSecretDataWithoutProperty,
  792. },
  793. want: want{
  794. err: noPermission,
  795. },
  796. },
  797. "SetSecretWrongGetSecretErrFails": {
  798. reason: "GetSecretValueWithContext errors out when anything except awssm.ErrCodeResourceNotFoundException",
  799. args: args{
  800. store: makeValidSecretStore().Spec.Provider.AWS,
  801. client: fakesm.Client{
  802. GetSecretValueFn: fakesm.NewGetSecretValueFn(blankSecretValueOutput, &getSecretWrongErr),
  803. },
  804. pushSecretData: pushSecretDataWithoutProperty,
  805. },
  806. want: want{
  807. err: &getSecretWrongErr,
  808. },
  809. },
  810. "SetSecretDescribeSecretFails": {
  811. reason: "secret cannot be described",
  812. args: args{
  813. store: makeValidSecretStore().Spec.Provider.AWS,
  814. client: fakesm.Client{
  815. GetSecretValueFn: fakesm.NewGetSecretValueFn(secretValueOutput, nil),
  816. DescribeSecretFn: fakesm.NewDescribeSecretFn(nil, noPermission),
  817. },
  818. pushSecretData: pushSecretDataWithoutProperty,
  819. },
  820. want: want{
  821. err: noPermission,
  822. },
  823. },
  824. "SetSecretDoesNotOverwriteUntaggedSecret": {
  825. reason: "secret cannot be described",
  826. args: args{
  827. store: makeValidSecretStore().Spec.Provider.AWS,
  828. client: fakesm.Client{
  829. GetSecretValueFn: fakesm.NewGetSecretValueFn(secretValueOutput, nil),
  830. DescribeSecretFn: fakesm.NewDescribeSecretFn(tagSecretOutputFaulty, nil),
  831. },
  832. pushSecretData: pushSecretDataWithoutProperty,
  833. },
  834. want: want{
  835. err: errors.New("secret not managed by external-secrets"),
  836. },
  837. },
  838. "PatchSecretTags": {
  839. reason: "secret key is configured with tags to remove and add",
  840. args: args{
  841. store: &esv1.AWSProvider{
  842. Service: esv1.AWSServiceSecretsManager,
  843. Region: "eu-west-2",
  844. },
  845. client: fakesm.Client{
  846. GetSecretValueFn: fakesm.NewGetSecretValueFn(secretValueOutputFrom(params{s: `{"fake-property":{"fake-property":"fake-value"}}`}), nil),
  847. DescribeSecretFn: fakesm.NewDescribeSecretFn(&awssm.DescribeSecretOutput{
  848. ARN: &arn,
  849. Tags: []types.Tag{
  850. {Key: &managedBy, Value: &externalSecrets},
  851. {Key: ptr.To("team"), Value: ptr.To("paradox")},
  852. },
  853. }, nil),
  854. PutSecretValueFn: fakesm.NewPutSecretValueFn(putSecretOutput, nil),
  855. TagResourceFn: fakesm.NewTagResourceFn(&awssm.TagResourceOutput{}, nil, func(input *awssm.TagResourceInput) {
  856. assert.Len(t, input.Tags, 2)
  857. assert.Contains(t, input.Tags, types.Tag{Key: &managedBy, Value: &externalSecrets})
  858. assert.Contains(t, input.Tags, types.Tag{Key: ptr.To("env"), Value: ptr.To("sandbox")})
  859. }),
  860. UntagResourceFn: fakesm.NewUntagResourceFn(&awssm.UntagResourceOutput{}, nil, func(input *awssm.UntagResourceInput) {
  861. assert.Len(t, input.TagKeys, 1)
  862. assert.Equal(t, []string{"team"}, input.TagKeys)
  863. assert.NotContains(t, input.TagKeys, managedBy)
  864. }),
  865. },
  866. pushSecretData: fake.PushSecretData{SecretKey: secretKey, RemoteKey: fakeKey, Property: "", Metadata: &apiextensionsv1.JSON{
  867. Raw: []byte(`{
  868. "apiVersion": "kubernetes.external-secrets.io/v1alpha1",
  869. "kind": "PushSecretMetadata",
  870. "spec": {
  871. "secretPushFormat": "string",
  872. "tags": {
  873. "env": "sandbox"
  874. }
  875. }
  876. }`)}},
  877. },
  878. want: want{
  879. err: nil,
  880. },
  881. },
  882. }
  883. for name, tc := range tests {
  884. t.Run(name, func(t *testing.T) {
  885. sm := SecretsManager{
  886. client: &tc.args.client,
  887. prefix: tc.args.store.Prefix,
  888. }
  889. err := sm.PushSecret(context.Background(), fakeSecret, tc.args.pushSecretData)
  890. // Error nil XOR tc.want.err nil
  891. if ((err == nil) || (tc.want.err == nil)) && !((err == nil) && (tc.want.err == nil)) {
  892. t.Errorf("\nTesting SetSecret:\nName: %v\nReason: %v\nWant error: %v\nGot error: %v", name, tc.reason, tc.want.err, err)
  893. }
  894. // if errors are the same type but their contents do not match
  895. if err != nil && tc.want.err != nil {
  896. if !strings.Contains(err.Error(), tc.want.err.Error()) {
  897. t.Errorf("\nTesting SetSecret:\nName: %v\nReason: %v\nWant error: %v\nGot error got nil", name, tc.reason, tc.want.err)
  898. }
  899. }
  900. })
  901. }
  902. }
  903. func TestDeleteSecret(t *testing.T) {
  904. fakeClient := fakesm.Client{}
  905. managed := managedBy
  906. manager := externalSecrets
  907. secretTag := types.Tag{
  908. Key: &managed,
  909. Value: &manager,
  910. }
  911. type args struct {
  912. client fakesm.Client
  913. config esv1.SecretsManager
  914. prefix string
  915. getSecretOutput *awssm.GetSecretValueOutput
  916. describeSecretOutput *awssm.DescribeSecretOutput
  917. deleteSecretOutput *awssm.DeleteSecretOutput
  918. getSecretErr error
  919. describeSecretErr error
  920. deleteSecretErr error
  921. }
  922. type want struct {
  923. err error
  924. }
  925. type testCase struct {
  926. args args
  927. want want
  928. reason string
  929. }
  930. tests := map[string]testCase{
  931. "Deletes Successfully": {
  932. args: args{
  933. client: fakeClient,
  934. config: esv1.SecretsManager{},
  935. getSecretOutput: &awssm.GetSecretValueOutput{},
  936. describeSecretOutput: &awssm.DescribeSecretOutput{
  937. Tags: []types.Tag{secretTag},
  938. },
  939. deleteSecretOutput: &awssm.DeleteSecretOutput{},
  940. getSecretErr: nil,
  941. describeSecretErr: nil,
  942. deleteSecretErr: nil,
  943. },
  944. want: want{
  945. err: nil,
  946. },
  947. reason: "",
  948. },
  949. "Deletes Successfully with ForceDeleteWithoutRecovery": {
  950. args: args{
  951. client: fakeClient,
  952. config: esv1.SecretsManager{
  953. ForceDeleteWithoutRecovery: true,
  954. },
  955. getSecretOutput: &awssm.GetSecretValueOutput{},
  956. describeSecretOutput: &awssm.DescribeSecretOutput{
  957. Tags: []types.Tag{secretTag},
  958. },
  959. deleteSecretOutput: &awssm.DeleteSecretOutput{
  960. DeletionDate: aws.Time(time.Now()),
  961. },
  962. getSecretErr: nil,
  963. describeSecretErr: nil,
  964. deleteSecretErr: nil,
  965. },
  966. want: want{
  967. err: nil,
  968. },
  969. reason: "",
  970. },
  971. "Not Managed by ESO": {
  972. args: args{
  973. client: fakeClient,
  974. config: esv1.SecretsManager{},
  975. getSecretOutput: &awssm.GetSecretValueOutput{},
  976. describeSecretOutput: &awssm.DescribeSecretOutput{
  977. Tags: []types.Tag{},
  978. },
  979. deleteSecretOutput: &awssm.DeleteSecretOutput{},
  980. getSecretErr: nil,
  981. describeSecretErr: nil,
  982. deleteSecretErr: nil,
  983. },
  984. want: want{
  985. err: nil,
  986. },
  987. reason: "",
  988. },
  989. "Invalid Recovery Window": {
  990. args: args{
  991. client: fakesm.Client{},
  992. config: esv1.SecretsManager{
  993. RecoveryWindowInDays: 1,
  994. },
  995. getSecretOutput: &awssm.GetSecretValueOutput{},
  996. describeSecretOutput: &awssm.DescribeSecretOutput{
  997. Tags: []types.Tag{secretTag},
  998. },
  999. deleteSecretOutput: &awssm.DeleteSecretOutput{},
  1000. getSecretErr: nil,
  1001. describeSecretErr: nil,
  1002. deleteSecretErr: nil,
  1003. },
  1004. want: want{
  1005. err: errors.New("invalid DeleteSecretInput: RecoveryWindowInDays must be between 7 and 30 days"),
  1006. },
  1007. reason: "",
  1008. },
  1009. "RecoveryWindowInDays is supplied with ForceDeleteWithoutRecovery": {
  1010. args: args{
  1011. client: fakesm.Client{},
  1012. config: esv1.SecretsManager{
  1013. RecoveryWindowInDays: 7,
  1014. ForceDeleteWithoutRecovery: true,
  1015. },
  1016. getSecretOutput: &awssm.GetSecretValueOutput{},
  1017. describeSecretOutput: &awssm.DescribeSecretOutput{
  1018. Tags: []types.Tag{secretTag},
  1019. },
  1020. deleteSecretOutput: &awssm.DeleteSecretOutput{},
  1021. getSecretErr: nil,
  1022. describeSecretErr: nil,
  1023. deleteSecretErr: nil,
  1024. },
  1025. want: want{
  1026. err: errors.New("invalid DeleteSecretInput: ForceDeleteWithoutRecovery conflicts with RecoveryWindowInDays"),
  1027. },
  1028. reason: "",
  1029. },
  1030. "Failed to get Tags": {
  1031. args: args{
  1032. client: fakeClient,
  1033. config: esv1.SecretsManager{},
  1034. getSecretOutput: &awssm.GetSecretValueOutput{},
  1035. describeSecretOutput: nil,
  1036. deleteSecretOutput: nil,
  1037. getSecretErr: nil,
  1038. describeSecretErr: errors.New("failed to get tags"),
  1039. deleteSecretErr: nil,
  1040. },
  1041. want: want{
  1042. err: errors.New("failed to get tags"),
  1043. },
  1044. reason: "",
  1045. },
  1046. "Secret Not Found": {
  1047. args: args{
  1048. client: fakeClient,
  1049. config: esv1.SecretsManager{},
  1050. getSecretOutput: nil,
  1051. describeSecretOutput: nil,
  1052. deleteSecretOutput: nil,
  1053. getSecretErr: errors.New("not here, sorry dude"),
  1054. describeSecretErr: nil,
  1055. deleteSecretErr: nil,
  1056. },
  1057. want: want{
  1058. err: errors.New("not here, sorry dude"),
  1059. },
  1060. },
  1061. "Not expected AWS error": {
  1062. args: args{
  1063. client: fakeClient,
  1064. config: esv1.SecretsManager{},
  1065. getSecretOutput: nil,
  1066. describeSecretOutput: nil,
  1067. deleteSecretOutput: nil,
  1068. getSecretErr: errors.New("aws unavailable"),
  1069. describeSecretErr: nil,
  1070. deleteSecretErr: nil,
  1071. },
  1072. want: want{
  1073. err: errors.New("aws unavailable"),
  1074. },
  1075. },
  1076. "unexpected error": {
  1077. args: args{
  1078. client: fakeClient,
  1079. config: esv1.SecretsManager{},
  1080. getSecretOutput: nil,
  1081. describeSecretOutput: nil,
  1082. deleteSecretOutput: nil,
  1083. getSecretErr: errors.New("timeout"),
  1084. describeSecretErr: nil,
  1085. deleteSecretErr: nil,
  1086. },
  1087. want: want{
  1088. err: errors.New("timeout"),
  1089. },
  1090. },
  1091. "DeleteWithPrefix": {
  1092. args: args{
  1093. client: fakesm.Client{
  1094. GetSecretValueFn: func(ctx context.Context, input *awssm.GetSecretValueInput, opts ...func(*awssm.Options)) (*awssm.GetSecretValueOutput, error) {
  1095. // Verify that the input secret ID has the prefix applied
  1096. if *input.SecretId != "my-prefix-"+fakeKey {
  1097. return nil, fmt.Errorf("expected secret name to be prefixed with 'my-prefix-', got %s", *input.SecretId)
  1098. }
  1099. return &awssm.GetSecretValueOutput{}, nil
  1100. },
  1101. DescribeSecretFn: func(ctx context.Context, input *awssm.DescribeSecretInput, opts ...func(*awssm.Options)) (*awssm.DescribeSecretOutput, error) {
  1102. // Verify that the input secret ID has the prefix applied
  1103. if *input.SecretId != "my-prefix-"+fakeKey {
  1104. return nil, fmt.Errorf("expected secret name to be prefixed with 'my-prefix-', got %s", *input.SecretId)
  1105. }
  1106. return &awssm.DescribeSecretOutput{
  1107. Tags: []types.Tag{secretTag},
  1108. }, nil
  1109. },
  1110. DeleteSecretFn: func(ctx context.Context, input *awssm.DeleteSecretInput, opts ...func(*awssm.Options)) (*awssm.DeleteSecretOutput, error) {
  1111. return &awssm.DeleteSecretOutput{}, nil
  1112. },
  1113. },
  1114. config: esv1.SecretsManager{},
  1115. prefix: "my-prefix-",
  1116. getSecretOutput: nil,
  1117. describeSecretOutput: nil,
  1118. deleteSecretOutput: nil,
  1119. getSecretErr: nil,
  1120. describeSecretErr: nil,
  1121. deleteSecretErr: nil,
  1122. },
  1123. want: want{
  1124. err: nil,
  1125. },
  1126. reason: "Verifies that the prefix is correctly applied when deleting a secret",
  1127. },
  1128. }
  1129. for name, tc := range tests {
  1130. t.Run(name, func(t *testing.T) {
  1131. ref := fake.PushSecretData{RemoteKey: fakeKey}
  1132. sm := SecretsManager{
  1133. client: &tc.args.client,
  1134. config: &tc.args.config,
  1135. prefix: tc.args.prefix,
  1136. }
  1137. if tc.args.client.GetSecretValueFn == nil {
  1138. tc.args.client.GetSecretValueFn = fakesm.NewGetSecretValueFn(tc.args.getSecretOutput, tc.args.getSecretErr)
  1139. }
  1140. if tc.args.client.DescribeSecretFn == nil {
  1141. tc.args.client.DescribeSecretFn = fakesm.NewDescribeSecretFn(tc.args.describeSecretOutput, tc.args.describeSecretErr)
  1142. }
  1143. if tc.args.client.DeleteSecretFn == nil {
  1144. tc.args.client.DeleteSecretFn = fakesm.NewDeleteSecretFn(tc.args.deleteSecretOutput, tc.args.deleteSecretErr)
  1145. }
  1146. err := sm.DeleteSecret(context.TODO(), ref)
  1147. t.Logf("DeleteSecret error: %v", err)
  1148. // Error nil XOR tc.want.err nil
  1149. if ((err == nil) || (tc.want.err == nil)) && !((err == nil) && (tc.want.err == nil)) {
  1150. t.Errorf("\nTesting DeleteSecret:\nName: %v\nReason: %v\nWant error: %v\nGot error: %v", name, tc.reason, tc.want.err, err)
  1151. }
  1152. // if errors are the same type but their contents do not match
  1153. if err != nil && tc.want.err != nil {
  1154. if !strings.Contains(err.Error(), tc.want.err.Error()) {
  1155. t.Errorf("\nTesting DeleteSecret:\nName: %v\nReason: %v\nWant error: %v\nGot error got nil", name, tc.reason, tc.want.err)
  1156. }
  1157. }
  1158. })
  1159. }
  1160. }
  1161. func makeValidSecretStore() *esv1.SecretStore {
  1162. return &esv1.SecretStore{
  1163. ObjectMeta: metav1.ObjectMeta{
  1164. Name: "aws-secret-store",
  1165. Namespace: "default",
  1166. },
  1167. Spec: esv1.SecretStoreSpec{
  1168. Provider: &esv1.SecretStoreProvider{
  1169. AWS: &esv1.AWSProvider{
  1170. Service: esv1.AWSServiceSecretsManager,
  1171. Region: "eu-west-2",
  1172. },
  1173. },
  1174. },
  1175. }
  1176. }
  1177. func getTagSlice() []types.Tag {
  1178. tagKey1 := tagname1
  1179. tagValue1 := tagvalue1
  1180. tagKey2 := tagname2
  1181. tagValue2 := tagvalue2
  1182. return []types.Tag{
  1183. {
  1184. Key: &tagKey1,
  1185. Value: &tagValue1,
  1186. },
  1187. {
  1188. Key: &tagKey2,
  1189. Value: &tagValue2,
  1190. },
  1191. }
  1192. }
  1193. func TestSecretsManagerGetAllSecrets(t *testing.T) {
  1194. ctx := context.Background()
  1195. errBoom := errors.New("boom")
  1196. secretName := "my-secret"
  1197. secretVersion := "AWSCURRENT"
  1198. secretPath := "/path/to/secret"
  1199. secretValue := "secret value"
  1200. secretTags := map[string]string{
  1201. "foo": "bar",
  1202. }
  1203. // Test cases
  1204. testCases := []struct {
  1205. name string
  1206. ref esv1.ExternalSecretFind
  1207. secretName string
  1208. secretVersion string
  1209. secretValue string
  1210. batchGetSecretValueFn func(context.Context, *awssm.BatchGetSecretValueInput, ...func(*awssm.Options)) (*awssm.BatchGetSecretValueOutput, error)
  1211. listSecretsFn func(context.Context, *awssm.ListSecretsInput, ...func(*awssm.Options)) (*awssm.ListSecretsOutput, error)
  1212. expectedData map[string][]byte
  1213. expectedError string
  1214. }{
  1215. {
  1216. name: "Matching secrets found",
  1217. ref: esv1.ExternalSecretFind{
  1218. Name: &esv1.FindName{
  1219. RegExp: secretName,
  1220. },
  1221. Path: ptr.To(secretPath),
  1222. },
  1223. secretName: secretName,
  1224. secretVersion: secretVersion,
  1225. secretValue: secretValue,
  1226. batchGetSecretValueFn: func(_ context.Context, input *awssm.BatchGetSecretValueInput, _ ...func(*awssm.Options)) (*awssm.BatchGetSecretValueOutput, error) {
  1227. assert.Len(t, input.Filters, 1)
  1228. assert.Equal(t, "name", string(input.Filters[0].Key))
  1229. assert.Equal(t, secretPath, input.Filters[0].Values[0])
  1230. return &awssm.BatchGetSecretValueOutput{
  1231. SecretValues: []types.SecretValueEntry{
  1232. {
  1233. Name: ptr.To(secretName),
  1234. VersionStages: []string{secretVersion},
  1235. SecretBinary: []byte(secretValue),
  1236. },
  1237. },
  1238. }, nil
  1239. },
  1240. expectedData: map[string][]byte{
  1241. secretName: []byte(secretValue),
  1242. },
  1243. expectedError: "",
  1244. },
  1245. {
  1246. name: "Error occurred while fetching secret value",
  1247. ref: esv1.ExternalSecretFind{
  1248. Name: &esv1.FindName{
  1249. RegExp: secretName,
  1250. },
  1251. Path: ptr.To(secretPath),
  1252. },
  1253. secretName: secretName,
  1254. secretVersion: secretVersion,
  1255. secretValue: secretValue,
  1256. batchGetSecretValueFn: func(_ context.Context, input *awssm.BatchGetSecretValueInput, _ ...func(*awssm.Options)) (*awssm.BatchGetSecretValueOutput, error) {
  1257. return &awssm.BatchGetSecretValueOutput{
  1258. SecretValues: []types.SecretValueEntry{
  1259. {
  1260. Name: ptr.To(secretName),
  1261. },
  1262. },
  1263. }, errBoom
  1264. },
  1265. expectedData: nil,
  1266. expectedError: errBoom.Error(),
  1267. },
  1268. {
  1269. name: "regexp: error occurred while listing secrets",
  1270. ref: esv1.ExternalSecretFind{
  1271. Name: &esv1.FindName{
  1272. RegExp: secretName,
  1273. },
  1274. },
  1275. listSecretsFn: func(_ context.Context, input *awssm.ListSecretsInput, _ ...func(*awssm.Options)) (*awssm.ListSecretsOutput, error) {
  1276. return nil, errBoom
  1277. },
  1278. expectedData: nil,
  1279. expectedError: errBoom.Error(),
  1280. },
  1281. {
  1282. name: "regep: no matching secrets found",
  1283. ref: esv1.ExternalSecretFind{
  1284. Name: &esv1.FindName{
  1285. RegExp: secretName,
  1286. },
  1287. },
  1288. listSecretsFn: func(_ context.Context, input *awssm.ListSecretsInput, _ ...func(*awssm.Options)) (*awssm.ListSecretsOutput, error) {
  1289. return &awssm.ListSecretsOutput{
  1290. SecretList: []types.SecretListEntry{
  1291. {
  1292. Name: ptr.To("other-secret"),
  1293. },
  1294. },
  1295. }, nil
  1296. },
  1297. batchGetSecretValueFn: func(_ context.Context, input *awssm.BatchGetSecretValueInput, _ ...func(*awssm.Options)) (*awssm.BatchGetSecretValueOutput, error) {
  1298. return &awssm.BatchGetSecretValueOutput{
  1299. SecretValues: []types.SecretValueEntry{
  1300. {
  1301. Name: ptr.To("other-secret"),
  1302. },
  1303. },
  1304. }, nil
  1305. },
  1306. expectedData: make(map[string][]byte),
  1307. expectedError: "",
  1308. },
  1309. {
  1310. name: "invalid regexp",
  1311. ref: esv1.ExternalSecretFind{
  1312. Name: &esv1.FindName{
  1313. RegExp: "[",
  1314. },
  1315. },
  1316. expectedData: nil,
  1317. expectedError: "could not compile find.name.regexp [[]: error parsing regexp: missing closing ]: `[`",
  1318. },
  1319. {
  1320. name: "tags: Matching secrets found",
  1321. ref: esv1.ExternalSecretFind{
  1322. Tags: secretTags,
  1323. },
  1324. secretName: secretName,
  1325. secretVersion: secretVersion,
  1326. secretValue: secretValue,
  1327. batchGetSecretValueFn: func(_ context.Context, input *awssm.BatchGetSecretValueInput, _ ...func(*awssm.Options)) (*awssm.BatchGetSecretValueOutput, error) {
  1328. assert.Len(t, input.Filters, 2)
  1329. assert.Equal(t, "tag-key", string(input.Filters[0].Key))
  1330. assert.Equal(t, "foo", input.Filters[0].Values[0])
  1331. assert.Equal(t, "tag-value", string(input.Filters[1].Key))
  1332. assert.Equal(t, "bar", input.Filters[1].Values[0])
  1333. return &awssm.BatchGetSecretValueOutput{
  1334. SecretValues: []types.SecretValueEntry{
  1335. {
  1336. Name: ptr.To(secretName),
  1337. VersionStages: []string{secretVersion},
  1338. SecretBinary: []byte(secretValue),
  1339. },
  1340. },
  1341. }, nil
  1342. },
  1343. expectedData: map[string][]byte{
  1344. secretName: []byte(secretValue),
  1345. },
  1346. expectedError: "",
  1347. },
  1348. {
  1349. name: "tags: error occurred while fetching secret value",
  1350. ref: esv1.ExternalSecretFind{
  1351. Tags: secretTags,
  1352. },
  1353. secretName: secretName,
  1354. secretVersion: secretVersion,
  1355. secretValue: secretValue,
  1356. batchGetSecretValueFn: func(_ context.Context, input *awssm.BatchGetSecretValueInput, _ ...func(*awssm.Options)) (*awssm.BatchGetSecretValueOutput, error) {
  1357. return &awssm.BatchGetSecretValueOutput{
  1358. SecretValues: []types.SecretValueEntry{
  1359. {
  1360. Name: ptr.To(secretName),
  1361. VersionStages: []string{secretVersion},
  1362. SecretBinary: []byte(secretValue),
  1363. },
  1364. },
  1365. }, errBoom
  1366. },
  1367. expectedData: nil,
  1368. expectedError: errBoom.Error(),
  1369. },
  1370. {
  1371. name: "tags: error occurred while listing secrets",
  1372. ref: esv1.ExternalSecretFind{
  1373. Tags: secretTags,
  1374. },
  1375. batchGetSecretValueFn: func(_ context.Context, input *awssm.BatchGetSecretValueInput, _ ...func(*awssm.Options)) (*awssm.BatchGetSecretValueOutput, error) {
  1376. return nil, errBoom
  1377. },
  1378. expectedData: nil,
  1379. expectedError: errBoom.Error(),
  1380. },
  1381. }
  1382. for _, tc := range testCases {
  1383. t.Run(tc.name, func(t *testing.T) {
  1384. fc := fakesm.NewClient()
  1385. fc.BatchGetSecretValueFn = tc.batchGetSecretValueFn
  1386. fc.ListSecretsFn = tc.listSecretsFn
  1387. sm := SecretsManager{
  1388. client: fc,
  1389. cache: make(map[string]*awssm.GetSecretValueOutput),
  1390. }
  1391. data, err := sm.GetAllSecrets(ctx, tc.ref)
  1392. if err != nil && err.Error() != tc.expectedError {
  1393. t.Errorf("unexpected error: got %v, want %v", err, tc.expectedError)
  1394. }
  1395. if !reflect.DeepEqual(data, tc.expectedData) {
  1396. t.Errorf("unexpected data: got %v, want %v", data, tc.expectedData)
  1397. }
  1398. })
  1399. }
  1400. }
  1401. func TestSecretsManagerValidate(t *testing.T) {
  1402. type fields struct {
  1403. cfg *aws.Config
  1404. referentAuth bool
  1405. }
  1406. validConfig := &aws.Config{
  1407. Credentials: credentials.NewStaticCredentialsProvider(
  1408. "fake",
  1409. "fake",
  1410. "fake",
  1411. ),
  1412. }
  1413. invalidConfig := &aws.Config{
  1414. Credentials: &FakeCredProvider{
  1415. retrieveFunc: func() (aws.Credentials, error) {
  1416. return aws.Credentials{}, errors.New("invalid credentials")
  1417. },
  1418. },
  1419. }
  1420. tests := []struct {
  1421. name string
  1422. fields fields
  1423. want esv1.ValidationResult
  1424. wantErr bool
  1425. }{
  1426. {
  1427. name: "ReferentAuth should always return unknown",
  1428. fields: fields{
  1429. referentAuth: true,
  1430. },
  1431. want: esv1.ValidationResultUnknown,
  1432. },
  1433. {
  1434. name: "Valid credentials should return ready",
  1435. fields: fields{
  1436. cfg: validConfig,
  1437. },
  1438. want: esv1.ValidationResultReady,
  1439. },
  1440. {
  1441. name: "Invalid credentials should return error",
  1442. fields: fields{
  1443. cfg: invalidConfig,
  1444. },
  1445. want: esv1.ValidationResultError,
  1446. wantErr: true,
  1447. },
  1448. }
  1449. for _, tt := range tests {
  1450. t.Run(tt.name, func(t *testing.T) {
  1451. sm := &SecretsManager{
  1452. cfg: tt.fields.cfg,
  1453. referentAuth: tt.fields.referentAuth,
  1454. }
  1455. got, err := sm.Validate()
  1456. if (err != nil) != tt.wantErr {
  1457. t.Errorf("SecretsManager.Validate() error = %v, wantErr %v", err, tt.wantErr)
  1458. return
  1459. }
  1460. if !reflect.DeepEqual(got, tt.want) {
  1461. t.Errorf("SecretsManager.Validate() = %v, want %v", got, tt.want)
  1462. }
  1463. })
  1464. }
  1465. }
  1466. func TestSecretExists(t *testing.T) {
  1467. arn := "arn:aws:secretsmanager:us-east-1:702902267788:secret:foo-bar5-Robbgh"
  1468. defaultVersion := "00000000-0000-0000-0000-000000000002"
  1469. secretValueOutput := &awssm.GetSecretValueOutput{
  1470. ARN: &arn,
  1471. VersionId: &defaultVersion,
  1472. }
  1473. blankSecretValueOutput := &awssm.GetSecretValueOutput{}
  1474. getSecretCorrectErr := types.ResourceNotFoundException{}
  1475. getSecretWrongErr := types.InvalidRequestException{}
  1476. pushSecretDataWithoutProperty := fake.PushSecretData{SecretKey: "fake-secret-key", RemoteKey: fakeKey, Property: ""}
  1477. type args struct {
  1478. store *esv1.AWSProvider
  1479. client fakesm.Client
  1480. pushSecretData fake.PushSecretData
  1481. }
  1482. type want struct {
  1483. err error
  1484. wantError bool
  1485. }
  1486. tests := map[string]struct {
  1487. args args
  1488. want want
  1489. }{
  1490. "SecretExistsReturnsTrueForExistingSecret": {
  1491. args: args{
  1492. store: makeValidSecretStore().Spec.Provider.AWS,
  1493. client: fakesm.Client{
  1494. GetSecretValueFn: fakesm.NewGetSecretValueFn(secretValueOutput, nil),
  1495. },
  1496. pushSecretData: pushSecretDataWithoutProperty,
  1497. },
  1498. want: want{
  1499. err: nil,
  1500. wantError: true,
  1501. },
  1502. },
  1503. "SecretExistsReturnsFalseForNonExistingSecret": {
  1504. args: args{
  1505. store: makeValidSecretStore().Spec.Provider.AWS,
  1506. client: fakesm.Client{
  1507. GetSecretValueFn: fakesm.NewGetSecretValueFn(blankSecretValueOutput, &getSecretCorrectErr),
  1508. },
  1509. pushSecretData: pushSecretDataWithoutProperty,
  1510. },
  1511. want: want{
  1512. err: nil,
  1513. wantError: false,
  1514. },
  1515. },
  1516. "SecretExistsReturnsFalseForErroredSecret": {
  1517. args: args{
  1518. store: makeValidSecretStore().Spec.Provider.AWS,
  1519. client: fakesm.Client{
  1520. GetSecretValueFn: fakesm.NewGetSecretValueFn(blankSecretValueOutput, &getSecretWrongErr),
  1521. },
  1522. pushSecretData: pushSecretDataWithoutProperty,
  1523. },
  1524. want: want{
  1525. err: &getSecretWrongErr,
  1526. wantError: false,
  1527. },
  1528. },
  1529. }
  1530. for name, tc := range tests {
  1531. t.Run(name, func(t *testing.T) {
  1532. sm := &SecretsManager{
  1533. client: &tc.args.client,
  1534. }
  1535. got, err := sm.SecretExists(context.Background(), tc.args.pushSecretData)
  1536. assert.Equal(
  1537. t,
  1538. tc.want,
  1539. want{
  1540. err: err,
  1541. wantError: got,
  1542. })
  1543. })
  1544. }
  1545. }
  1546. func TestConstructMetadataWithDefaults(t *testing.T) {
  1547. tests := []struct {
  1548. name string
  1549. input *apiextensionsv1.JSON
  1550. expected *metadata.PushSecretMetadata[PushSecretMetadataSpec]
  1551. expectError bool
  1552. }{
  1553. {
  1554. name: "Valid metadata with multiple fields",
  1555. input: &apiextensionsv1.JSON{Raw: []byte(`{
  1556. "apiVersion": "kubernetes.external-secrets.io/v1alpha1",
  1557. "kind": "PushSecretMetadata",
  1558. "spec": {
  1559. "description": "test description",
  1560. "secretPushFormat":"string",
  1561. "kmsKeyID": "custom-kms-key",
  1562. "tags": {
  1563. "customKey": "customValue"
  1564. },
  1565. }
  1566. }`)},
  1567. expected: &metadata.PushSecretMetadata[PushSecretMetadataSpec]{
  1568. APIVersion: "kubernetes.external-secrets.io/v1alpha1",
  1569. Kind: "PushSecretMetadata",
  1570. Spec: PushSecretMetadataSpec{
  1571. Description: "test description",
  1572. SecretPushFormat: "string",
  1573. KMSKeyID: "custom-kms-key",
  1574. Tags: map[string]string{
  1575. "customKey": "customValue",
  1576. managedBy: externalSecrets,
  1577. },
  1578. },
  1579. },
  1580. },
  1581. {
  1582. name: "Empty metadata, defaults applied",
  1583. input: nil,
  1584. expected: &metadata.PushSecretMetadata[PushSecretMetadataSpec]{
  1585. Spec: PushSecretMetadataSpec{
  1586. Description: fmt.Sprintf("secret '%s:%s'", managedBy, externalSecrets),
  1587. SecretPushFormat: "binary",
  1588. KMSKeyID: "alias/aws/secretsmanager",
  1589. Tags: map[string]string{
  1590. managedBy: externalSecrets,
  1591. },
  1592. },
  1593. },
  1594. },
  1595. {
  1596. name: "Added default metadata with 'managed-by' tag",
  1597. input: &apiextensionsv1.JSON{Raw: []byte(`{
  1598. "apiVersion": "kubernetes.external-secrets.io/v1alpha1",
  1599. "kind": "PushSecretMetadata",
  1600. "spec": {
  1601. "tags": {
  1602. "managed-by": "external-secrets",
  1603. "customKey": "customValue"
  1604. },
  1605. }
  1606. }`)},
  1607. expected: nil,
  1608. expectError: true,
  1609. },
  1610. {
  1611. name: "Invalid metadata format",
  1612. input: &apiextensionsv1.JSON{Raw: []byte(`invalid-json`)},
  1613. expected: nil,
  1614. expectError: true,
  1615. },
  1616. {
  1617. name: "Metadata with 'managed-by' tag specified",
  1618. input: &apiextensionsv1.JSON{Raw: []byte(`{"tags":{"managed-by":"invalid"}}`)},
  1619. expected: nil,
  1620. expectError: true,
  1621. },
  1622. }
  1623. for _, tt := range tests {
  1624. t.Run(tt.name, func(t *testing.T) {
  1625. result, err := (&SecretsManager{}).constructMetadataWithDefaults(tt.input)
  1626. if tt.expectError {
  1627. assert.Error(t, err)
  1628. } else {
  1629. assert.NoError(t, err)
  1630. assert.Equal(t, tt.expected, result)
  1631. }
  1632. })
  1633. }
  1634. }
  1635. func TestComputeTagsToUpdate(t *testing.T) {
  1636. tests := []struct {
  1637. name string
  1638. tags map[string]string
  1639. metaTags map[string]string
  1640. expected []types.Tag
  1641. modified bool
  1642. }{
  1643. {
  1644. name: "No tags to update",
  1645. tags: map[string]string{
  1646. "key1": "value1",
  1647. "key2": "value2",
  1648. },
  1649. metaTags: map[string]string{
  1650. "key1": "value1",
  1651. "key2": "value2",
  1652. },
  1653. expected: []types.Tag{
  1654. {Key: ptr.To("key1"), Value: ptr.To("value1")},
  1655. {Key: ptr.To("key2"), Value: ptr.To("value2")},
  1656. },
  1657. modified: false,
  1658. },
  1659. {
  1660. name: "No tags to update as managed-by tag is ignored",
  1661. tags: map[string]string{
  1662. "key1": "value1",
  1663. "key2": "value2",
  1664. },
  1665. metaTags: map[string]string{
  1666. "key1": "value1",
  1667. "key2": "value2",
  1668. managedBy: externalSecrets,
  1669. },
  1670. expected: []types.Tag{
  1671. {Key: ptr.To("key1"), Value: ptr.To("value1")},
  1672. {Key: ptr.To("key2"), Value: ptr.To("value2")},
  1673. {Key: ptr.To(managedBy), Value: ptr.To(externalSecrets)},
  1674. },
  1675. modified: false,
  1676. },
  1677. {
  1678. name: "Add new tag",
  1679. tags: map[string]string{
  1680. "key1": "value1",
  1681. },
  1682. metaTags: map[string]string{
  1683. "key1": "value1",
  1684. "key2": "value2",
  1685. },
  1686. expected: []types.Tag{
  1687. {Key: ptr.To("key1"), Value: ptr.To("value1")},
  1688. {Key: ptr.To("key2"), Value: ptr.To("value2")},
  1689. },
  1690. modified: true,
  1691. },
  1692. {
  1693. name: "Update existing tag value",
  1694. tags: map[string]string{
  1695. "key1": "value1",
  1696. },
  1697. metaTags: map[string]string{
  1698. "key1": "newValue",
  1699. },
  1700. expected: []types.Tag{
  1701. {Key: ptr.To("key1"), Value: ptr.To("newValue")},
  1702. },
  1703. modified: true,
  1704. },
  1705. {
  1706. name: "Empty tags and metaTags",
  1707. tags: map[string]string{},
  1708. metaTags: map[string]string{},
  1709. expected: []types.Tag{},
  1710. modified: false,
  1711. },
  1712. {
  1713. name: "Empty tags with non-empty metaTags",
  1714. tags: map[string]string{},
  1715. metaTags: map[string]string{
  1716. "key1": "value1",
  1717. },
  1718. expected: []types.Tag{
  1719. {Key: ptr.To("key1"), Value: ptr.To("value1")},
  1720. },
  1721. modified: true,
  1722. },
  1723. }
  1724. for _, tt := range tests {
  1725. t.Run(tt.name, func(t *testing.T) {
  1726. result, modified := computeTagsToUpdate(tt.tags, tt.metaTags)
  1727. assert.ElementsMatch(t, tt.expected, result)
  1728. assert.Equal(t, tt.modified, modified)
  1729. })
  1730. }
  1731. }
  1732. func TestPatchTags(t *testing.T) {
  1733. type call struct {
  1734. untagCalled bool
  1735. tagCalled bool
  1736. }
  1737. tests := []struct {
  1738. name string
  1739. existingTags map[string]string
  1740. metaTags map[string]string
  1741. expectUntag bool
  1742. expectTag bool
  1743. assertsTag func(input *awssm.TagResourceInput)
  1744. assertsUntag func(input *awssm.UntagResourceInput)
  1745. }{
  1746. {
  1747. name: "no changes",
  1748. existingTags: map[string]string{"a": "1"},
  1749. metaTags: map[string]string{"a": "1"},
  1750. expectUntag: false,
  1751. expectTag: false,
  1752. assertsTag: func(input *awssm.TagResourceInput) {
  1753. assert.Fail(t, "Expected TagResource to not be called")
  1754. },
  1755. assertsUntag: func(input *awssm.UntagResourceInput) {
  1756. assert.Fail(t, "Expected UntagResource to not be called")
  1757. },
  1758. },
  1759. {
  1760. name: "update tag value",
  1761. existingTags: map[string]string{"a": "1"},
  1762. metaTags: map[string]string{"a": "2"},
  1763. expectUntag: false,
  1764. expectTag: true,
  1765. assertsTag: func(input *awssm.TagResourceInput) {
  1766. assert.Contains(t, input.Tags, types.Tag{Key: ptr.To(managedBy), Value: ptr.To(externalSecrets)})
  1767. assert.Contains(t, input.Tags, types.Tag{Key: ptr.To("a"), Value: ptr.To("2")})
  1768. },
  1769. assertsUntag: func(input *awssm.UntagResourceInput) {
  1770. assert.Fail(t, "Expected UntagResource to not be called")
  1771. },
  1772. },
  1773. {
  1774. name: "remove tag",
  1775. existingTags: map[string]string{"a": "1", "b": "2"},
  1776. metaTags: map[string]string{"a": "1"},
  1777. expectUntag: true,
  1778. expectTag: false,
  1779. assertsTag: func(input *awssm.TagResourceInput) {
  1780. assert.Fail(t, "Expected TagResource to not be called")
  1781. },
  1782. assertsUntag: func(input *awssm.UntagResourceInput) {
  1783. assert.Equal(t, []string{"b"}, input.TagKeys)
  1784. },
  1785. },
  1786. {
  1787. name: "add tags",
  1788. existingTags: map[string]string{"a": "1"},
  1789. metaTags: map[string]string{"a": "1", "b": "2"},
  1790. expectUntag: false,
  1791. expectTag: true,
  1792. assertsTag: func(input *awssm.TagResourceInput) {
  1793. assert.Contains(t, input.Tags, types.Tag{Key: ptr.To(managedBy), Value: ptr.To(externalSecrets)})
  1794. assert.Contains(t, input.Tags, types.Tag{Key: ptr.To("a"), Value: ptr.To("1")})
  1795. assert.Contains(t, input.Tags, types.Tag{Key: ptr.To("b"), Value: ptr.To("2")})
  1796. },
  1797. assertsUntag: func(input *awssm.UntagResourceInput) {
  1798. assert.Fail(t, "Expected UntagResource to not be called")
  1799. },
  1800. },
  1801. }
  1802. for _, tt := range tests {
  1803. t.Run(tt.name, func(t *testing.T) {
  1804. calls := call{}
  1805. fakeClient := &fakesm.Client{
  1806. TagResourceFn: fakesm.NewTagResourceFn(&awssm.TagResourceOutput{}, nil, func(input *awssm.TagResourceInput) {
  1807. tt.assertsTag(input)
  1808. calls.tagCalled = true
  1809. }),
  1810. UntagResourceFn: fakesm.NewUntagResourceFn(&awssm.UntagResourceOutput{}, nil, func(input *awssm.UntagResourceInput) {
  1811. tt.assertsUntag(input)
  1812. calls.untagCalled = true
  1813. }),
  1814. }
  1815. sm := &SecretsManager{client: fakeClient}
  1816. metaMap := map[string]interface{}{
  1817. "apiVersion": "kubernetes.external-secrets.io/v1alpha1",
  1818. "kind": "PushSecretMetadata",
  1819. "spec": map[string]interface{}{
  1820. "description": "adding managed-by tag explicitly",
  1821. "tags": tt.metaTags,
  1822. },
  1823. }
  1824. raw, err := json.Marshal(metaMap)
  1825. require.NoError(t, err)
  1826. meta := &apiextensionsv1.JSON{Raw: raw}
  1827. secretId := "secret"
  1828. err = sm.patchTags(context.Background(), meta, &secretId, tt.existingTags)
  1829. require.NoError(t, err)
  1830. assert.Equal(t, tt.expectUntag, calls.untagCalled)
  1831. assert.Equal(t, tt.expectTag, calls.tagCalled)
  1832. })
  1833. }
  1834. }
  1835. // FakeCredProvider implements the AWS credentials.Provider interface
  1836. // It is used to inject an error into the AWS config to cause a
  1837. // validation error.
  1838. type FakeCredProvider struct {
  1839. retrieveFunc func() (aws.Credentials, error)
  1840. }
  1841. func (f *FakeCredProvider) Retrieve(ctx context.Context) (aws.Credentials, error) {
  1842. return f.retrieveFunc()
  1843. }
  1844. func (f *FakeCredProvider) IsExpired() bool {
  1845. return true
  1846. }