secretsmanager_test.go 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009
  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. tagSecretOutputNoVersions := &awssm.DescribeSecretOutput{
  398. ARN: &arn,
  399. Tags: externalSecretsTag,
  400. }
  401. defaultVersion := "00000000-0000-0000-0000-000000000002"
  402. tagSecretOutput := &awssm.DescribeSecretOutput{
  403. ARN: &arn,
  404. Tags: externalSecretsTag,
  405. VersionIdsToStages: map[string][]string{
  406. defaultVersion: {"AWSCURRENT"},
  407. },
  408. }
  409. tagSecretOutputFaulty := &awssm.DescribeSecretOutput{
  410. ARN: &arn,
  411. Tags: externalSecretsTagFaulty,
  412. }
  413. tagSecretOutputFrom := func(versionId string) *awssm.DescribeSecretOutput {
  414. return &awssm.DescribeSecretOutput{
  415. ARN: &arn,
  416. Tags: externalSecretsTag,
  417. VersionIdsToStages: map[string][]string{
  418. versionId: {"AWSCURRENT"},
  419. },
  420. }
  421. }
  422. initialVersion := "00000000-0000-0000-0000-000000000001"
  423. defaultUpdatedVersion := "6c70d57a-f53d-bf4d-9525-3503dd5abe8c"
  424. randomUUIDVersion := "9d6202c2-c216-433e-a2f0-5836c4f025af"
  425. randomUUIDVersionIncremented := "4346824b-7da1-4d82-addf-dee197fd5d71"
  426. unparsableVersion := "IAM UNPARSABLE"
  427. secretValueOutput := &awssm.GetSecretValueOutput{
  428. ARN: &arn,
  429. VersionId: &defaultVersion,
  430. }
  431. secretValueOutput2 := &awssm.GetSecretValueOutput{
  432. ARN: &arn,
  433. SecretBinary: secretValue,
  434. VersionId: &defaultVersion,
  435. }
  436. blankDescribeSecretOutput := &awssm.DescribeSecretOutput{}
  437. type params struct {
  438. s string
  439. b []byte
  440. version *string
  441. }
  442. secretValueOutputFrom := func(params params) *awssm.GetSecretValueOutput {
  443. var version *string
  444. if params.version == nil {
  445. version = &defaultVersion
  446. } else {
  447. version = params.version
  448. }
  449. return &awssm.GetSecretValueOutput{
  450. ARN: &arn,
  451. SecretString: &params.s,
  452. SecretBinary: params.b,
  453. VersionId: version,
  454. }
  455. }
  456. putSecretOutput := &awssm.PutSecretValueOutput{
  457. ARN: &arn,
  458. }
  459. pushSecretDataWithoutProperty := fake.PushSecretData{SecretKey: secretKey, RemoteKey: fakeKey, Property: ""}
  460. pushSecretDataWithoutSecretKey := fake.PushSecretData{RemoteKey: fakeKey, Property: ""}
  461. pushSecretDataWithMetadata := fake.PushSecretData{SecretKey: secretKey, RemoteKey: fakeKey, Property: "", Metadata: &apiextensionsv1.JSON{
  462. Raw: []byte(`{
  463. "apiVersion": "kubernetes.external-secrets.io/v1alpha1",
  464. "kind": "PushSecretMetadata",
  465. "spec": {
  466. "secretPushFormat": "string"
  467. }
  468. }`)}}
  469. pushSecretDataWithProperty := fake.PushSecretData{SecretKey: secretKey, RemoteKey: fakeKey, Property: "other-fake-property"}
  470. type args struct {
  471. store *esv1.AWSProvider
  472. client fakesm.Client
  473. pushSecretData fake.PushSecretData
  474. newUUID string
  475. }
  476. type want struct {
  477. err error
  478. }
  479. tests := map[string]struct {
  480. reason string
  481. args args
  482. want want
  483. }{
  484. "SetSecretSucceedsWithExistingSecret": {
  485. reason: "a secret can be pushed to aws secrets manager when it already exists",
  486. args: args{
  487. store: makeValidSecretStore().Spec.Provider.AWS,
  488. client: fakesm.Client{
  489. GetSecretValueFn: fakesm.NewGetSecretValueFn(secretValueOutput, nil),
  490. PutSecretValueFn: fakesm.NewPutSecretValueFn(putSecretOutput, nil),
  491. DescribeSecretFn: fakesm.NewDescribeSecretFn(tagSecretOutput, nil),
  492. TagResourceFn: fakesm.NewTagResourceFn(&awssm.TagResourceOutput{}, nil),
  493. UntagResourceFn: fakesm.NewUntagResourceFn(&awssm.UntagResourceOutput{}, nil),
  494. },
  495. pushSecretData: pushSecretDataWithoutProperty,
  496. },
  497. want: want{
  498. err: nil,
  499. },
  500. },
  501. "SetSecretSucceedsWithExistingSecretButNoSecretVersionsWithoutProperty": {
  502. reason: "a secret can be pushed to aws secrets manager when it already exists but has no secret versions",
  503. args: args{
  504. store: makeValidSecretStore().Spec.Provider.AWS,
  505. client: fakesm.Client{
  506. DescribeSecretFn: fakesm.NewDescribeSecretFn(tagSecretOutputNoVersions, nil),
  507. PutSecretValueFn: fakesm.NewPutSecretValueFn(putSecretOutput, nil, fakesm.ExpectedPutSecretValueInput{
  508. SecretBinary: []byte(`fake-value`),
  509. Version: aws.String(initialVersion),
  510. }),
  511. TagResourceFn: fakesm.NewTagResourceFn(&awssm.TagResourceOutput{}, nil),
  512. UntagResourceFn: fakesm.NewUntagResourceFn(&awssm.UntagResourceOutput{}, nil),
  513. },
  514. pushSecretData: pushSecretDataWithoutProperty,
  515. },
  516. want: want{
  517. err: nil,
  518. },
  519. },
  520. "SetSecretSucceedsWithExistingSecretButNoSecretVersionsWithProperty": {
  521. reason: "a secret can be pushed to aws secrets manager when it already exists but has no secret versions",
  522. args: args{
  523. store: makeValidSecretStore().Spec.Provider.AWS,
  524. client: fakesm.Client{
  525. DescribeSecretFn: fakesm.NewDescribeSecretFn(tagSecretOutputNoVersions, nil),
  526. PutSecretValueFn: fakesm.NewPutSecretValueFn(putSecretOutput, nil, fakesm.ExpectedPutSecretValueInput{
  527. SecretBinary: []byte(`{"other-fake-property":"fake-value"}`),
  528. Version: aws.String(initialVersion),
  529. }),
  530. TagResourceFn: fakesm.NewTagResourceFn(&awssm.TagResourceOutput{}, nil),
  531. UntagResourceFn: fakesm.NewUntagResourceFn(&awssm.UntagResourceOutput{}, nil),
  532. },
  533. pushSecretData: pushSecretDataWithProperty,
  534. },
  535. want: want{
  536. err: nil,
  537. },
  538. },
  539. "SetSecretSucceedsWithoutSecretKey": {
  540. reason: "a secret can be pushed to aws secrets manager without secret key",
  541. args: args{
  542. store: makeValidSecretStore().Spec.Provider.AWS,
  543. client: fakesm.Client{
  544. GetSecretValueFn: fakesm.NewGetSecretValueFn(secretValueOutput, nil),
  545. PutSecretValueFn: fakesm.NewPutSecretValueFn(putSecretOutput, nil),
  546. DescribeSecretFn: fakesm.NewDescribeSecretFn(tagSecretOutput, nil),
  547. TagResourceFn: fakesm.NewTagResourceFn(&awssm.TagResourceOutput{}, nil),
  548. UntagResourceFn: fakesm.NewUntagResourceFn(&awssm.UntagResourceOutput{}, nil),
  549. },
  550. pushSecretData: pushSecretDataWithoutSecretKey,
  551. },
  552. want: want{
  553. err: nil,
  554. },
  555. },
  556. "SetSecretSucceedsWithExistingSecretAndStringFormat": {
  557. reason: "a secret can be pushed to aws secrets manager when it already exists",
  558. args: args{
  559. store: makeValidSecretStore().Spec.Provider.AWS,
  560. client: fakesm.Client{
  561. GetSecretValueFn: fakesm.NewGetSecretValueFn(secretValueOutput, nil),
  562. PutSecretValueFn: fakesm.NewPutSecretValueFn(putSecretOutput, nil),
  563. DescribeSecretFn: fakesm.NewDescribeSecretFn(tagSecretOutput, nil),
  564. TagResourceFn: fakesm.NewTagResourceFn(&awssm.TagResourceOutput{}, nil),
  565. UntagResourceFn: fakesm.NewUntagResourceFn(&awssm.UntagResourceOutput{}, nil),
  566. },
  567. pushSecretData: pushSecretDataWithMetadata,
  568. },
  569. want: want{
  570. err: nil,
  571. },
  572. },
  573. "SetSecretSucceedsWithExistingSecretAndKMSKeyAndDescription": {
  574. reason: "a secret can be pushed to aws secrets manager when it already exists",
  575. args: args{
  576. store: makeValidSecretStore().Spec.Provider.AWS,
  577. client: fakesm.Client{
  578. GetSecretValueFn: fakesm.NewGetSecretValueFn(secretValueOutput, &getSecretCorrectErr),
  579. PutSecretValueFn: fakesm.NewPutSecretValueFn(putSecretOutput, nil),
  580. DescribeSecretFn: fakesm.NewDescribeSecretFn(tagSecretOutput, nil),
  581. },
  582. pushSecretData: fake.PushSecretData{SecretKey: secretKey, RemoteKey: fakeKey, Property: "", Metadata: &apiextensionsv1.JSON{
  583. Raw: []byte(`{
  584. "apiVersion": "kubernetes.external-secrets.io/v1alpha1",
  585. "kind": "PushSecretMetadata",
  586. "spec": {
  587. "kmsKeyID": "bb123123-b2b0-4f60-ac3a-44a13f0e6b6c",
  588. "description": "this is a description"
  589. }
  590. }`)}},
  591. },
  592. want: want{
  593. err: &getSecretCorrectErr,
  594. },
  595. },
  596. "SetSecretSucceedsWithExistingSecretAndAdditionalTags": {
  597. reason: "a secret can be pushed to aws secrets manager when it already exists",
  598. args: args{
  599. store: makeValidSecretStore().Spec.Provider.AWS,
  600. client: fakesm.Client{
  601. GetSecretValueFn: fakesm.NewGetSecretValueFn(secretValueOutput, nil),
  602. PutSecretValueFn: fakesm.NewPutSecretValueFn(putSecretOutput, nil),
  603. DescribeSecretFn: fakesm.NewDescribeSecretFn(tagSecretOutput, nil),
  604. TagResourceFn: fakesm.NewTagResourceFn(&awssm.TagResourceOutput{}, nil),
  605. UntagResourceFn: fakesm.NewUntagResourceFn(&awssm.UntagResourceOutput{}, nil),
  606. },
  607. pushSecretData: fake.PushSecretData{SecretKey: secretKey, RemoteKey: fakeKey, Property: "", Metadata: &apiextensionsv1.JSON{
  608. Raw: []byte(`{
  609. "apiVersion": "kubernetes.external-secrets.io/v1alpha1",
  610. "kind": "PushSecretMetadata",
  611. "spec": {
  612. "tags": {"tagname12": "tagvalue1"}
  613. }
  614. }`)}},
  615. },
  616. want: want{
  617. err: nil,
  618. },
  619. },
  620. "SetSecretSucceedsWithNewSecret": {
  621. reason: "a secret can be pushed to aws secrets manager if it doesn't already exist",
  622. args: args{
  623. store: makeValidSecretStore().Spec.Provider.AWS,
  624. client: fakesm.Client{
  625. DescribeSecretFn: fakesm.NewDescribeSecretFn(blankDescribeSecretOutput, &getSecretCorrectErr),
  626. CreateSecretFn: fakesm.NewCreateSecretFn(secretOutput, nil),
  627. },
  628. pushSecretData: pushSecretDataWithoutProperty,
  629. },
  630. want: want{
  631. err: nil,
  632. },
  633. },
  634. "SetSecretWithPropertySucceedsWithNewSecret": {
  635. 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",
  636. args: args{
  637. store: makeValidSecretStore().Spec.Provider.AWS,
  638. client: fakesm.Client{
  639. DescribeSecretFn: fakesm.NewDescribeSecretFn(blankDescribeSecretOutput, &getSecretCorrectErr),
  640. CreateSecretFn: fakesm.NewCreateSecretFn(secretOutput, nil, []byte(`{"other-fake-property":"fake-value"}`)),
  641. },
  642. pushSecretData: pushSecretDataWithProperty,
  643. },
  644. want: want{
  645. err: nil,
  646. },
  647. },
  648. "SetSecretWithPropertySucceedsWithExistingSecretAndNewPropertyBinary": {
  649. 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)",
  650. args: args{
  651. newUUID: defaultUpdatedVersion,
  652. store: makeValidSecretStore().Spec.Provider.AWS,
  653. client: fakesm.Client{
  654. GetSecretValueFn: fakesm.NewGetSecretValueFn(secretValueOutputFrom(params{b: []byte((`{"fake-property":"fake-value"}`))}), nil),
  655. DescribeSecretFn: fakesm.NewDescribeSecretFn(tagSecretOutput, nil),
  656. PutSecretValueFn: fakesm.NewPutSecretValueFn(putSecretOutput, nil, fakesm.ExpectedPutSecretValueInput{
  657. SecretBinary: []byte(`{"fake-property":"fake-value","other-fake-property":"fake-value"}`),
  658. Version: &defaultUpdatedVersion,
  659. }),
  660. TagResourceFn: fakesm.NewTagResourceFn(&awssm.TagResourceOutput{}, nil),
  661. UntagResourceFn: fakesm.NewUntagResourceFn(&awssm.UntagResourceOutput{}, nil),
  662. },
  663. pushSecretData: pushSecretDataWithProperty,
  664. },
  665. want: want{
  666. err: nil,
  667. },
  668. },
  669. "SetSecretWithPropertySucceedsWithExistingSecretAndRandomUUIDVersion": {
  670. 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",
  671. args: args{
  672. store: makeValidSecretStore().Spec.Provider.AWS,
  673. newUUID: randomUUIDVersionIncremented,
  674. client: fakesm.Client{
  675. GetSecretValueFn: fakesm.NewGetSecretValueFn(secretValueOutputFrom(params{
  676. b: []byte((`{"fake-property":"fake-value"}`)),
  677. version: &randomUUIDVersion,
  678. }), nil),
  679. DescribeSecretFn: fakesm.NewDescribeSecretFn(tagSecretOutputFrom(randomUUIDVersion), nil),
  680. PutSecretValueFn: fakesm.NewPutSecretValueFn(putSecretOutput, nil, fakesm.ExpectedPutSecretValueInput{
  681. SecretBinary: []byte(`{"fake-property":"fake-value","other-fake-property":"fake-value"}`),
  682. Version: &randomUUIDVersionIncremented,
  683. }),
  684. TagResourceFn: fakesm.NewTagResourceFn(&awssm.TagResourceOutput{}, nil),
  685. UntagResourceFn: fakesm.NewUntagResourceFn(&awssm.UntagResourceOutput{}, nil),
  686. },
  687. pushSecretData: pushSecretDataWithProperty,
  688. },
  689. want: want{
  690. err: nil,
  691. },
  692. },
  693. "SetSecretWithPropertySucceedsWithExistingSecretAndVersionThatCantBeParsed": {
  694. reason: "A manually set secret version doesn't have to be a UUID",
  695. args: args{
  696. newUUID: unparsableVersion,
  697. store: makeValidSecretStore().Spec.Provider.AWS,
  698. client: fakesm.Client{
  699. GetSecretValueFn: fakesm.NewGetSecretValueFn(secretValueOutputFrom(params{
  700. b: []byte((`{"fake-property":"fake-value"}`)),
  701. version: &unparsableVersion,
  702. }), nil),
  703. DescribeSecretFn: fakesm.NewDescribeSecretFn(tagSecretOutput, nil),
  704. PutSecretValueFn: fakesm.NewPutSecretValueFn(putSecretOutput, nil, fakesm.ExpectedPutSecretValueInput{
  705. SecretBinary: []byte((`fake-value`)),
  706. Version: &unparsableVersion,
  707. }),
  708. TagResourceFn: fakesm.NewTagResourceFn(&awssm.TagResourceOutput{}, nil),
  709. UntagResourceFn: fakesm.NewUntagResourceFn(&awssm.UntagResourceOutput{}, nil),
  710. },
  711. pushSecretData: pushSecretDataWithoutProperty,
  712. },
  713. want: want{
  714. err: nil,
  715. },
  716. },
  717. "SetSecretWithPropertySucceedsWithExistingSecretAndAbsentVersion": {
  718. reason: "When a secret version is not specified, set it to 1",
  719. args: args{
  720. newUUID: initialVersion,
  721. store: makeValidSecretStore().Spec.Provider.AWS,
  722. client: fakesm.Client{
  723. GetSecretValueFn: fakesm.NewGetSecretValueFn(&awssm.GetSecretValueOutput{
  724. ARN: &arn,
  725. SecretBinary: []byte((`{"fake-property":"fake-value"}`)),
  726. }, nil),
  727. DescribeSecretFn: fakesm.NewDescribeSecretFn(tagSecretOutput, nil),
  728. PutSecretValueFn: fakesm.NewPutSecretValueFn(putSecretOutput, nil, fakesm.ExpectedPutSecretValueInput{
  729. SecretBinary: []byte(`{"fake-property":"fake-value","other-fake-property":"fake-value"}`),
  730. Version: &initialVersion,
  731. }),
  732. TagResourceFn: fakesm.NewTagResourceFn(&awssm.TagResourceOutput{}, nil),
  733. UntagResourceFn: fakesm.NewUntagResourceFn(&awssm.UntagResourceOutput{}, nil),
  734. },
  735. pushSecretData: pushSecretDataWithProperty,
  736. },
  737. want: want{
  738. err: nil,
  739. },
  740. },
  741. "SetSecretWithPropertySucceedsWithExistingSecretAndNewPropertyString": {
  742. 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)",
  743. args: args{
  744. newUUID: defaultUpdatedVersion,
  745. store: makeValidSecretStore().Spec.Provider.AWS,
  746. client: fakesm.Client{
  747. GetSecretValueFn: fakesm.NewGetSecretValueFn(secretValueOutputFrom(params{s: `{"fake-property":"fake-value"}`}), nil),
  748. DescribeSecretFn: fakesm.NewDescribeSecretFn(tagSecretOutput, nil),
  749. PutSecretValueFn: fakesm.NewPutSecretValueFn(putSecretOutput, nil, fakesm.ExpectedPutSecretValueInput{
  750. SecretBinary: []byte(`{"fake-property":"fake-value","other-fake-property":"fake-value"}`),
  751. Version: &defaultUpdatedVersion,
  752. }),
  753. TagResourceFn: fakesm.NewTagResourceFn(&awssm.TagResourceOutput{}, nil),
  754. UntagResourceFn: fakesm.NewUntagResourceFn(&awssm.UntagResourceOutput{}, nil),
  755. },
  756. pushSecretData: pushSecretDataWithProperty,
  757. },
  758. want: want{
  759. err: nil,
  760. },
  761. },
  762. "SetSecretWithPropertySucceedsWithExistingSecretAndNewPropertyWithDot": {
  763. 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)",
  764. args: args{
  765. newUUID: defaultUpdatedVersion,
  766. store: makeValidSecretStore().Spec.Provider.AWS,
  767. client: fakesm.Client{
  768. GetSecretValueFn: fakesm.NewGetSecretValueFn(secretValueOutputFrom(params{s: `{"fake-property":{"fake-property":"fake-value"}}`}), nil),
  769. DescribeSecretFn: fakesm.NewDescribeSecretFn(tagSecretOutput, nil),
  770. PutSecretValueFn: fakesm.NewPutSecretValueFn(putSecretOutput, nil, fakesm.ExpectedPutSecretValueInput{
  771. SecretBinary: []byte(`{"fake-property":{"fake-property":"fake-value","other-fake-property":"fake-value"}}`),
  772. Version: &defaultUpdatedVersion,
  773. }),
  774. TagResourceFn: fakesm.NewTagResourceFn(&awssm.TagResourceOutput{}, nil),
  775. UntagResourceFn: fakesm.NewUntagResourceFn(&awssm.UntagResourceOutput{}, nil),
  776. },
  777. pushSecretData: fake.PushSecretData{SecretKey: secretKey, RemoteKey: fakeKey, Property: "fake-property.other-fake-property"},
  778. },
  779. want: want{
  780. err: nil,
  781. },
  782. },
  783. "SetSecretWithPropertyFailsExistingNonJsonSecret": {
  784. reason: "setting a pushSecretData property is only supported for json secrets",
  785. args: args{
  786. store: makeValidSecretStore().Spec.Provider.AWS,
  787. client: fakesm.Client{
  788. GetSecretValueFn: fakesm.NewGetSecretValueFn(secretValueOutputFrom(params{s: `non-json-secret`}), nil),
  789. DescribeSecretFn: fakesm.NewDescribeSecretFn(tagSecretOutput, nil),
  790. },
  791. pushSecretData: pushSecretDataWithProperty,
  792. },
  793. want: want{
  794. err: errors.New("PushSecret for aws secrets manager with a pushSecretData property requires a json secret"),
  795. },
  796. },
  797. "SetSecretCreateSecretFails": {
  798. reason: "CreateSecretWithContext returns an error if it fails",
  799. args: args{
  800. store: makeValidSecretStore().Spec.Provider.AWS,
  801. client: fakesm.Client{
  802. DescribeSecretFn: fakesm.NewDescribeSecretFn(blankDescribeSecretOutput, &getSecretCorrectErr),
  803. CreateSecretFn: fakesm.NewCreateSecretFn(nil, noPermission),
  804. },
  805. pushSecretData: pushSecretDataWithoutProperty,
  806. },
  807. want: want{
  808. err: noPermission,
  809. },
  810. },
  811. "SetSecretGetSecretFails": {
  812. reason: "GetSecretValueWithContext returns an error if it fails",
  813. args: args{
  814. store: makeValidSecretStore().Spec.Provider.AWS,
  815. client: fakesm.Client{
  816. DescribeSecretFn: fakesm.NewDescribeSecretFn(blankDescribeSecretOutput, noPermission),
  817. },
  818. pushSecretData: pushSecretDataWithoutProperty,
  819. },
  820. want: want{
  821. err: noPermission,
  822. },
  823. },
  824. "SetSecretWillNotPushSameSecret": {
  825. reason: "secret with the same value will not be pushed",
  826. args: args{
  827. store: makeValidSecretStore().Spec.Provider.AWS,
  828. client: fakesm.Client{
  829. GetSecretValueFn: fakesm.NewGetSecretValueFn(secretValueOutput2, nil),
  830. DescribeSecretFn: fakesm.NewDescribeSecretFn(tagSecretOutput, nil),
  831. },
  832. pushSecretData: pushSecretDataWithoutProperty,
  833. },
  834. want: want{
  835. err: nil,
  836. },
  837. },
  838. "SetSecretPutSecretValueFails": {
  839. reason: "PutSecretValueWithContext returns an error if it fails",
  840. args: args{
  841. store: makeValidSecretStore().Spec.Provider.AWS,
  842. client: fakesm.Client{
  843. GetSecretValueFn: fakesm.NewGetSecretValueFn(secretValueOutput, nil),
  844. PutSecretValueFn: fakesm.NewPutSecretValueFn(nil, noPermission),
  845. DescribeSecretFn: fakesm.NewDescribeSecretFn(tagSecretOutput, nil),
  846. TagResourceFn: fakesm.NewTagResourceFn(&awssm.TagResourceOutput{}, nil),
  847. UntagResourceFn: fakesm.NewUntagResourceFn(&awssm.UntagResourceOutput{}, nil),
  848. },
  849. pushSecretData: pushSecretDataWithoutProperty,
  850. },
  851. want: want{
  852. err: noPermission,
  853. },
  854. },
  855. "SetSecretWrongGetSecretErrFails": {
  856. reason: "DescribeSecret errors out when anything except awssm.ErrCodeResourceNotFoundException",
  857. args: args{
  858. store: makeValidSecretStore().Spec.Provider.AWS,
  859. client: fakesm.Client{
  860. DescribeSecretFn: fakesm.NewDescribeSecretFn(blankDescribeSecretOutput, &getSecretWrongErr),
  861. },
  862. pushSecretData: pushSecretDataWithoutProperty,
  863. },
  864. want: want{
  865. err: &getSecretWrongErr,
  866. },
  867. },
  868. "SetSecretDescribeSecretFails": {
  869. reason: "secret cannot be described",
  870. args: args{
  871. store: makeValidSecretStore().Spec.Provider.AWS,
  872. client: fakesm.Client{
  873. GetSecretValueFn: fakesm.NewGetSecretValueFn(secretValueOutput, nil),
  874. DescribeSecretFn: fakesm.NewDescribeSecretFn(nil, noPermission),
  875. },
  876. pushSecretData: pushSecretDataWithoutProperty,
  877. },
  878. want: want{
  879. err: noPermission,
  880. },
  881. },
  882. "SetSecretDoesNotOverwriteUntaggedSecret": {
  883. reason: "secret cannot be described",
  884. args: args{
  885. store: makeValidSecretStore().Spec.Provider.AWS,
  886. client: fakesm.Client{
  887. GetSecretValueFn: fakesm.NewGetSecretValueFn(secretValueOutput, nil),
  888. DescribeSecretFn: fakesm.NewDescribeSecretFn(tagSecretOutputFaulty, nil),
  889. },
  890. pushSecretData: pushSecretDataWithoutProperty,
  891. },
  892. want: want{
  893. err: errors.New("secret not managed by external-secrets"),
  894. },
  895. },
  896. "PatchSecretTags": {
  897. reason: "secret key is configured with tags to remove and add",
  898. args: args{
  899. store: &esv1.AWSProvider{
  900. Service: esv1.AWSServiceSecretsManager,
  901. Region: "eu-west-2",
  902. },
  903. client: fakesm.Client{
  904. GetSecretValueFn: fakesm.NewGetSecretValueFn(secretValueOutputFrom(params{s: `{"fake-property":{"fake-property":"fake-value"}}`}), nil),
  905. DescribeSecretFn: fakesm.NewDescribeSecretFn(&awssm.DescribeSecretOutput{
  906. ARN: &arn,
  907. Tags: []types.Tag{
  908. {Key: &managedBy, Value: &externalSecrets},
  909. {Key: ptr.To("team"), Value: ptr.To("paradox")},
  910. },
  911. }, nil),
  912. PutSecretValueFn: fakesm.NewPutSecretValueFn(putSecretOutput, nil),
  913. TagResourceFn: fakesm.NewTagResourceFn(&awssm.TagResourceOutput{}, nil, func(input *awssm.TagResourceInput) {
  914. assert.Len(t, input.Tags, 2)
  915. assert.Contains(t, input.Tags, types.Tag{Key: &managedBy, Value: &externalSecrets})
  916. assert.Contains(t, input.Tags, types.Tag{Key: ptr.To("env"), Value: ptr.To("sandbox")})
  917. }),
  918. UntagResourceFn: fakesm.NewUntagResourceFn(&awssm.UntagResourceOutput{}, nil, func(input *awssm.UntagResourceInput) {
  919. assert.Len(t, input.TagKeys, 1)
  920. assert.Equal(t, []string{"team"}, input.TagKeys)
  921. assert.NotContains(t, input.TagKeys, managedBy)
  922. }),
  923. },
  924. pushSecretData: fake.PushSecretData{SecretKey: secretKey, RemoteKey: fakeKey, Property: "", Metadata: &apiextensionsv1.JSON{
  925. Raw: []byte(`{
  926. "apiVersion": "kubernetes.external-secrets.io/v1alpha1",
  927. "kind": "PushSecretMetadata",
  928. "spec": {
  929. "secretPushFormat": "string",
  930. "tags": {
  931. "env": "sandbox"
  932. }
  933. }
  934. }`)}},
  935. },
  936. want: want{
  937. err: nil,
  938. },
  939. },
  940. }
  941. for name, tc := range tests {
  942. t.Run(name, func(t *testing.T) {
  943. sm := SecretsManager{
  944. client: &tc.args.client,
  945. prefix: tc.args.store.Prefix,
  946. newUUID: func() string { return tc.args.newUUID },
  947. }
  948. err := sm.PushSecret(context.Background(), fakeSecret, tc.args.pushSecretData)
  949. // Error nil XOR tc.want.err nil
  950. if ((err == nil) || (tc.want.err == nil)) && !((err == nil) && (tc.want.err == nil)) {
  951. t.Errorf("\nTesting SetSecret:\nName: %v\nReason: %v\nWant error: %v\nGot error: %v", name, tc.reason, tc.want.err, err)
  952. }
  953. // if errors are the same type but their contents do not match
  954. if err != nil && tc.want.err != nil {
  955. if !strings.Contains(err.Error(), tc.want.err.Error()) {
  956. t.Errorf("\nTesting SetSecret:\nName: %v\nReason: %v\nWant error: %v\nGot error got nil", name, tc.reason, tc.want.err)
  957. }
  958. }
  959. })
  960. }
  961. }
  962. func TestDeleteSecret(t *testing.T) {
  963. fakeClient := fakesm.Client{}
  964. managed := managedBy
  965. manager := externalSecrets
  966. secretTag := types.Tag{
  967. Key: &managed,
  968. Value: &manager,
  969. }
  970. type args struct {
  971. client fakesm.Client
  972. config esv1.SecretsManager
  973. prefix string
  974. getSecretOutput *awssm.GetSecretValueOutput
  975. describeSecretOutput *awssm.DescribeSecretOutput
  976. deleteSecretOutput *awssm.DeleteSecretOutput
  977. getSecretErr error
  978. describeSecretErr error
  979. deleteSecretErr error
  980. }
  981. type want struct {
  982. err error
  983. }
  984. type testCase struct {
  985. args args
  986. want want
  987. reason string
  988. }
  989. tests := map[string]testCase{
  990. "Deletes Successfully": {
  991. args: args{
  992. client: fakeClient,
  993. config: esv1.SecretsManager{},
  994. getSecretOutput: &awssm.GetSecretValueOutput{},
  995. describeSecretOutput: &awssm.DescribeSecretOutput{
  996. Tags: []types.Tag{secretTag},
  997. },
  998. deleteSecretOutput: &awssm.DeleteSecretOutput{},
  999. getSecretErr: nil,
  1000. describeSecretErr: nil,
  1001. deleteSecretErr: nil,
  1002. },
  1003. want: want{
  1004. err: nil,
  1005. },
  1006. reason: "",
  1007. },
  1008. "Deletes Successfully with ForceDeleteWithoutRecovery": {
  1009. args: args{
  1010. client: fakeClient,
  1011. config: esv1.SecretsManager{
  1012. ForceDeleteWithoutRecovery: true,
  1013. },
  1014. getSecretOutput: &awssm.GetSecretValueOutput{},
  1015. describeSecretOutput: &awssm.DescribeSecretOutput{
  1016. Tags: []types.Tag{secretTag},
  1017. },
  1018. deleteSecretOutput: &awssm.DeleteSecretOutput{
  1019. DeletionDate: aws.Time(time.Now()),
  1020. },
  1021. getSecretErr: nil,
  1022. describeSecretErr: nil,
  1023. deleteSecretErr: nil,
  1024. },
  1025. want: want{
  1026. err: nil,
  1027. },
  1028. reason: "",
  1029. },
  1030. "Not Managed by ESO": {
  1031. args: args{
  1032. client: fakeClient,
  1033. config: esv1.SecretsManager{},
  1034. getSecretOutput: &awssm.GetSecretValueOutput{},
  1035. describeSecretOutput: &awssm.DescribeSecretOutput{
  1036. Tags: []types.Tag{},
  1037. },
  1038. deleteSecretOutput: &awssm.DeleteSecretOutput{},
  1039. getSecretErr: nil,
  1040. describeSecretErr: nil,
  1041. deleteSecretErr: nil,
  1042. },
  1043. want: want{
  1044. err: nil,
  1045. },
  1046. reason: "",
  1047. },
  1048. "Invalid Recovery Window": {
  1049. args: args{
  1050. client: fakesm.Client{},
  1051. config: esv1.SecretsManager{
  1052. RecoveryWindowInDays: 1,
  1053. },
  1054. getSecretOutput: &awssm.GetSecretValueOutput{},
  1055. describeSecretOutput: &awssm.DescribeSecretOutput{
  1056. Tags: []types.Tag{secretTag},
  1057. },
  1058. deleteSecretOutput: &awssm.DeleteSecretOutput{},
  1059. getSecretErr: nil,
  1060. describeSecretErr: nil,
  1061. deleteSecretErr: nil,
  1062. },
  1063. want: want{
  1064. err: errors.New("invalid DeleteSecretInput: RecoveryWindowInDays must be between 7 and 30 days"),
  1065. },
  1066. reason: "",
  1067. },
  1068. "RecoveryWindowInDays is supplied with ForceDeleteWithoutRecovery": {
  1069. args: args{
  1070. client: fakesm.Client{},
  1071. config: esv1.SecretsManager{
  1072. RecoveryWindowInDays: 7,
  1073. ForceDeleteWithoutRecovery: true,
  1074. },
  1075. getSecretOutput: &awssm.GetSecretValueOutput{},
  1076. describeSecretOutput: &awssm.DescribeSecretOutput{
  1077. Tags: []types.Tag{secretTag},
  1078. },
  1079. deleteSecretOutput: &awssm.DeleteSecretOutput{},
  1080. getSecretErr: nil,
  1081. describeSecretErr: nil,
  1082. deleteSecretErr: nil,
  1083. },
  1084. want: want{
  1085. err: errors.New("invalid DeleteSecretInput: ForceDeleteWithoutRecovery conflicts with RecoveryWindowInDays"),
  1086. },
  1087. reason: "",
  1088. },
  1089. "Failed to get Tags": {
  1090. args: args{
  1091. client: fakeClient,
  1092. config: esv1.SecretsManager{},
  1093. getSecretOutput: &awssm.GetSecretValueOutput{},
  1094. describeSecretOutput: nil,
  1095. deleteSecretOutput: nil,
  1096. getSecretErr: nil,
  1097. describeSecretErr: errors.New("failed to get tags"),
  1098. deleteSecretErr: nil,
  1099. },
  1100. want: want{
  1101. err: errors.New("failed to get tags"),
  1102. },
  1103. reason: "",
  1104. },
  1105. "Secret Not Found": {
  1106. args: args{
  1107. client: fakeClient,
  1108. config: esv1.SecretsManager{},
  1109. getSecretOutput: nil,
  1110. describeSecretOutput: nil,
  1111. deleteSecretOutput: nil,
  1112. getSecretErr: errors.New("not here, sorry dude"),
  1113. describeSecretErr: nil,
  1114. deleteSecretErr: nil,
  1115. },
  1116. want: want{
  1117. err: errors.New("not here, sorry dude"),
  1118. },
  1119. },
  1120. "Not expected AWS error": {
  1121. args: args{
  1122. client: fakeClient,
  1123. config: esv1.SecretsManager{},
  1124. getSecretOutput: nil,
  1125. describeSecretOutput: nil,
  1126. deleteSecretOutput: nil,
  1127. getSecretErr: errors.New("aws unavailable"),
  1128. describeSecretErr: nil,
  1129. deleteSecretErr: nil,
  1130. },
  1131. want: want{
  1132. err: errors.New("aws unavailable"),
  1133. },
  1134. },
  1135. "unexpected error": {
  1136. args: args{
  1137. client: fakeClient,
  1138. config: esv1.SecretsManager{},
  1139. getSecretOutput: nil,
  1140. describeSecretOutput: nil,
  1141. deleteSecretOutput: nil,
  1142. getSecretErr: errors.New("timeout"),
  1143. describeSecretErr: nil,
  1144. deleteSecretErr: nil,
  1145. },
  1146. want: want{
  1147. err: errors.New("timeout"),
  1148. },
  1149. },
  1150. "DeleteWithPrefix": {
  1151. args: args{
  1152. client: fakesm.Client{
  1153. GetSecretValueFn: func(ctx context.Context, input *awssm.GetSecretValueInput, opts ...func(*awssm.Options)) (*awssm.GetSecretValueOutput, error) {
  1154. // Verify that the input secret ID has the prefix applied
  1155. if *input.SecretId != "my-prefix-"+fakeKey {
  1156. return nil, fmt.Errorf("expected secret name to be prefixed with 'my-prefix-', got %s", *input.SecretId)
  1157. }
  1158. return &awssm.GetSecretValueOutput{}, nil
  1159. },
  1160. DescribeSecretFn: func(ctx context.Context, input *awssm.DescribeSecretInput, opts ...func(*awssm.Options)) (*awssm.DescribeSecretOutput, error) {
  1161. // Verify that the input secret ID has the prefix applied
  1162. if *input.SecretId != "my-prefix-"+fakeKey {
  1163. return nil, fmt.Errorf("expected secret name to be prefixed with 'my-prefix-', got %s", *input.SecretId)
  1164. }
  1165. return &awssm.DescribeSecretOutput{
  1166. Tags: []types.Tag{secretTag},
  1167. }, nil
  1168. },
  1169. DeleteSecretFn: func(ctx context.Context, input *awssm.DeleteSecretInput, opts ...func(*awssm.Options)) (*awssm.DeleteSecretOutput, error) {
  1170. return &awssm.DeleteSecretOutput{}, nil
  1171. },
  1172. },
  1173. config: esv1.SecretsManager{},
  1174. prefix: "my-prefix-",
  1175. getSecretOutput: nil,
  1176. describeSecretOutput: nil,
  1177. deleteSecretOutput: nil,
  1178. getSecretErr: nil,
  1179. describeSecretErr: nil,
  1180. deleteSecretErr: nil,
  1181. },
  1182. want: want{
  1183. err: nil,
  1184. },
  1185. reason: "Verifies that the prefix is correctly applied when deleting a secret",
  1186. },
  1187. }
  1188. for name, tc := range tests {
  1189. t.Run(name, func(t *testing.T) {
  1190. ref := fake.PushSecretData{RemoteKey: fakeKey}
  1191. sm := SecretsManager{
  1192. client: &tc.args.client,
  1193. config: &tc.args.config,
  1194. prefix: tc.args.prefix,
  1195. }
  1196. if tc.args.client.GetSecretValueFn == nil {
  1197. tc.args.client.GetSecretValueFn = fakesm.NewGetSecretValueFn(tc.args.getSecretOutput, tc.args.getSecretErr)
  1198. }
  1199. if tc.args.client.DescribeSecretFn == nil {
  1200. tc.args.client.DescribeSecretFn = fakesm.NewDescribeSecretFn(tc.args.describeSecretOutput, tc.args.describeSecretErr)
  1201. }
  1202. if tc.args.client.DeleteSecretFn == nil {
  1203. tc.args.client.DeleteSecretFn = fakesm.NewDeleteSecretFn(tc.args.deleteSecretOutput, tc.args.deleteSecretErr)
  1204. }
  1205. err := sm.DeleteSecret(context.TODO(), ref)
  1206. t.Logf("DeleteSecret error: %v", err)
  1207. // Error nil XOR tc.want.err nil
  1208. if ((err == nil) || (tc.want.err == nil)) && !((err == nil) && (tc.want.err == nil)) {
  1209. t.Errorf("\nTesting DeleteSecret:\nName: %v\nReason: %v\nWant error: %v\nGot error: %v", name, tc.reason, tc.want.err, err)
  1210. }
  1211. // if errors are the same type but their contents do not match
  1212. if err != nil && tc.want.err != nil {
  1213. if !strings.Contains(err.Error(), tc.want.err.Error()) {
  1214. t.Errorf("\nTesting DeleteSecret:\nName: %v\nReason: %v\nWant error: %v\nGot error got nil", name, tc.reason, tc.want.err)
  1215. }
  1216. }
  1217. })
  1218. }
  1219. }
  1220. func makeValidSecretStore() *esv1.SecretStore {
  1221. return &esv1.SecretStore{
  1222. ObjectMeta: metav1.ObjectMeta{
  1223. Name: "aws-secret-store",
  1224. Namespace: "default",
  1225. },
  1226. Spec: esv1.SecretStoreSpec{
  1227. Provider: &esv1.SecretStoreProvider{
  1228. AWS: &esv1.AWSProvider{
  1229. Service: esv1.AWSServiceSecretsManager,
  1230. Region: "eu-west-2",
  1231. },
  1232. },
  1233. },
  1234. }
  1235. }
  1236. func getTagSlice() []types.Tag {
  1237. tagKey1 := tagname1
  1238. tagValue1 := tagvalue1
  1239. tagKey2 := tagname2
  1240. tagValue2 := tagvalue2
  1241. return []types.Tag{
  1242. {
  1243. Key: &tagKey1,
  1244. Value: &tagValue1,
  1245. },
  1246. {
  1247. Key: &tagKey2,
  1248. Value: &tagValue2,
  1249. },
  1250. }
  1251. }
  1252. func TestSecretsManagerGetAllSecrets(t *testing.T) {
  1253. ctx := context.Background()
  1254. errBoom := errors.New("boom")
  1255. secretName := "my-secret"
  1256. secretVersion := "AWSCURRENT"
  1257. secretPath := "/path/to/secret"
  1258. secretValue := "secret value"
  1259. secretTags := map[string]string{
  1260. "foo": "bar",
  1261. }
  1262. // Test cases
  1263. testCases := []struct {
  1264. name string
  1265. ref esv1.ExternalSecretFind
  1266. secretName string
  1267. secretVersion string
  1268. secretValue string
  1269. batchGetSecretValueFn func(context.Context, *awssm.BatchGetSecretValueInput, ...func(*awssm.Options)) (*awssm.BatchGetSecretValueOutput, error)
  1270. listSecretsFn func(context.Context, *awssm.ListSecretsInput, ...func(*awssm.Options)) (*awssm.ListSecretsOutput, error)
  1271. expectedData map[string][]byte
  1272. expectedError string
  1273. }{
  1274. {
  1275. name: "Matching secrets found",
  1276. ref: esv1.ExternalSecretFind{
  1277. Name: &esv1.FindName{
  1278. RegExp: secretName,
  1279. },
  1280. Path: ptr.To(secretPath),
  1281. },
  1282. secretName: secretName,
  1283. secretVersion: secretVersion,
  1284. secretValue: secretValue,
  1285. batchGetSecretValueFn: func(_ context.Context, input *awssm.BatchGetSecretValueInput, _ ...func(*awssm.Options)) (*awssm.BatchGetSecretValueOutput, error) {
  1286. assert.Len(t, input.Filters, 1)
  1287. assert.Equal(t, "name", string(input.Filters[0].Key))
  1288. assert.Equal(t, secretPath, input.Filters[0].Values[0])
  1289. return &awssm.BatchGetSecretValueOutput{
  1290. SecretValues: []types.SecretValueEntry{
  1291. {
  1292. Name: ptr.To(secretName),
  1293. VersionStages: []string{secretVersion},
  1294. SecretBinary: []byte(secretValue),
  1295. },
  1296. },
  1297. }, nil
  1298. },
  1299. expectedData: map[string][]byte{
  1300. secretName: []byte(secretValue),
  1301. },
  1302. expectedError: "",
  1303. },
  1304. {
  1305. name: "Error occurred while fetching secret value",
  1306. ref: esv1.ExternalSecretFind{
  1307. Name: &esv1.FindName{
  1308. RegExp: secretName,
  1309. },
  1310. Path: ptr.To(secretPath),
  1311. },
  1312. secretName: secretName,
  1313. secretVersion: secretVersion,
  1314. secretValue: secretValue,
  1315. batchGetSecretValueFn: func(_ context.Context, input *awssm.BatchGetSecretValueInput, _ ...func(*awssm.Options)) (*awssm.BatchGetSecretValueOutput, error) {
  1316. return &awssm.BatchGetSecretValueOutput{
  1317. SecretValues: []types.SecretValueEntry{
  1318. {
  1319. Name: ptr.To(secretName),
  1320. },
  1321. },
  1322. }, errBoom
  1323. },
  1324. expectedData: nil,
  1325. expectedError: errBoom.Error(),
  1326. },
  1327. {
  1328. name: "regexp: error occurred while listing secrets",
  1329. ref: esv1.ExternalSecretFind{
  1330. Name: &esv1.FindName{
  1331. RegExp: secretName,
  1332. },
  1333. },
  1334. listSecretsFn: func(_ context.Context, input *awssm.ListSecretsInput, _ ...func(*awssm.Options)) (*awssm.ListSecretsOutput, error) {
  1335. return nil, errBoom
  1336. },
  1337. expectedData: nil,
  1338. expectedError: errBoom.Error(),
  1339. },
  1340. {
  1341. name: "regep: no matching secrets found",
  1342. ref: esv1.ExternalSecretFind{
  1343. Name: &esv1.FindName{
  1344. RegExp: secretName,
  1345. },
  1346. },
  1347. listSecretsFn: func(_ context.Context, input *awssm.ListSecretsInput, _ ...func(*awssm.Options)) (*awssm.ListSecretsOutput, error) {
  1348. return &awssm.ListSecretsOutput{
  1349. SecretList: []types.SecretListEntry{
  1350. {
  1351. Name: ptr.To("other-secret"),
  1352. },
  1353. },
  1354. }, nil
  1355. },
  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("other-secret"),
  1361. },
  1362. },
  1363. }, nil
  1364. },
  1365. expectedData: make(map[string][]byte),
  1366. expectedError: "",
  1367. },
  1368. {
  1369. name: "invalid regexp",
  1370. ref: esv1.ExternalSecretFind{
  1371. Name: &esv1.FindName{
  1372. RegExp: "[",
  1373. },
  1374. },
  1375. expectedData: nil,
  1376. expectedError: "could not compile find.name.regexp [[]: error parsing regexp: missing closing ]: `[`",
  1377. },
  1378. {
  1379. name: "tags: Matching secrets found",
  1380. ref: esv1.ExternalSecretFind{
  1381. Tags: secretTags,
  1382. },
  1383. secretName: secretName,
  1384. secretVersion: secretVersion,
  1385. secretValue: secretValue,
  1386. batchGetSecretValueFn: func(_ context.Context, input *awssm.BatchGetSecretValueInput, _ ...func(*awssm.Options)) (*awssm.BatchGetSecretValueOutput, error) {
  1387. assert.Len(t, input.Filters, 2)
  1388. assert.Equal(t, "tag-key", string(input.Filters[0].Key))
  1389. assert.Equal(t, "foo", input.Filters[0].Values[0])
  1390. assert.Equal(t, "tag-value", string(input.Filters[1].Key))
  1391. assert.Equal(t, "bar", input.Filters[1].Values[0])
  1392. return &awssm.BatchGetSecretValueOutput{
  1393. SecretValues: []types.SecretValueEntry{
  1394. {
  1395. Name: ptr.To(secretName),
  1396. VersionStages: []string{secretVersion},
  1397. SecretBinary: []byte(secretValue),
  1398. },
  1399. },
  1400. }, nil
  1401. },
  1402. expectedData: map[string][]byte{
  1403. secretName: []byte(secretValue),
  1404. },
  1405. expectedError: "",
  1406. },
  1407. {
  1408. name: "tags: error occurred while fetching secret value",
  1409. ref: esv1.ExternalSecretFind{
  1410. Tags: secretTags,
  1411. },
  1412. secretName: secretName,
  1413. secretVersion: secretVersion,
  1414. secretValue: secretValue,
  1415. batchGetSecretValueFn: func(_ context.Context, input *awssm.BatchGetSecretValueInput, _ ...func(*awssm.Options)) (*awssm.BatchGetSecretValueOutput, error) {
  1416. return &awssm.BatchGetSecretValueOutput{
  1417. SecretValues: []types.SecretValueEntry{
  1418. {
  1419. Name: ptr.To(secretName),
  1420. VersionStages: []string{secretVersion},
  1421. SecretBinary: []byte(secretValue),
  1422. },
  1423. },
  1424. }, errBoom
  1425. },
  1426. expectedData: nil,
  1427. expectedError: errBoom.Error(),
  1428. },
  1429. {
  1430. name: "tags: error occurred while listing secrets",
  1431. ref: esv1.ExternalSecretFind{
  1432. Tags: secretTags,
  1433. },
  1434. batchGetSecretValueFn: func(_ context.Context, input *awssm.BatchGetSecretValueInput, _ ...func(*awssm.Options)) (*awssm.BatchGetSecretValueOutput, error) {
  1435. return nil, errBoom
  1436. },
  1437. expectedData: nil,
  1438. expectedError: errBoom.Error(),
  1439. },
  1440. }
  1441. for _, tc := range testCases {
  1442. t.Run(tc.name, func(t *testing.T) {
  1443. fc := fakesm.NewClient()
  1444. fc.BatchGetSecretValueFn = tc.batchGetSecretValueFn
  1445. fc.ListSecretsFn = tc.listSecretsFn
  1446. sm := SecretsManager{
  1447. client: fc,
  1448. cache: make(map[string]*awssm.GetSecretValueOutput),
  1449. }
  1450. data, err := sm.GetAllSecrets(ctx, tc.ref)
  1451. if err != nil && err.Error() != tc.expectedError {
  1452. t.Errorf("unexpected error: got %v, want %v", err, tc.expectedError)
  1453. }
  1454. if !reflect.DeepEqual(data, tc.expectedData) {
  1455. t.Errorf("unexpected data: got %v, want %v", data, tc.expectedData)
  1456. }
  1457. })
  1458. }
  1459. }
  1460. func TestSecretsManagerValidate(t *testing.T) {
  1461. type fields struct {
  1462. cfg *aws.Config
  1463. referentAuth bool
  1464. }
  1465. validConfig := &aws.Config{
  1466. Credentials: credentials.NewStaticCredentialsProvider(
  1467. "fake",
  1468. "fake",
  1469. "fake",
  1470. ),
  1471. }
  1472. invalidConfig := &aws.Config{
  1473. Credentials: &FakeCredProvider{
  1474. retrieveFunc: func() (aws.Credentials, error) {
  1475. return aws.Credentials{}, errors.New("invalid credentials")
  1476. },
  1477. },
  1478. }
  1479. tests := []struct {
  1480. name string
  1481. fields fields
  1482. want esv1.ValidationResult
  1483. wantErr bool
  1484. }{
  1485. {
  1486. name: "ReferentAuth should always return unknown",
  1487. fields: fields{
  1488. referentAuth: true,
  1489. },
  1490. want: esv1.ValidationResultUnknown,
  1491. },
  1492. {
  1493. name: "Valid credentials should return ready",
  1494. fields: fields{
  1495. cfg: validConfig,
  1496. },
  1497. want: esv1.ValidationResultReady,
  1498. },
  1499. {
  1500. name: "Invalid credentials should return error",
  1501. fields: fields{
  1502. cfg: invalidConfig,
  1503. },
  1504. want: esv1.ValidationResultError,
  1505. wantErr: true,
  1506. },
  1507. }
  1508. for _, tt := range tests {
  1509. t.Run(tt.name, func(t *testing.T) {
  1510. sm := &SecretsManager{
  1511. cfg: tt.fields.cfg,
  1512. referentAuth: tt.fields.referentAuth,
  1513. }
  1514. got, err := sm.Validate()
  1515. if (err != nil) != tt.wantErr {
  1516. t.Errorf("SecretsManager.Validate() error = %v, wantErr %v", err, tt.wantErr)
  1517. return
  1518. }
  1519. if !reflect.DeepEqual(got, tt.want) {
  1520. t.Errorf("SecretsManager.Validate() = %v, want %v", got, tt.want)
  1521. }
  1522. })
  1523. }
  1524. }
  1525. func TestSecretExists(t *testing.T) {
  1526. arn := "arn:aws:secretsmanager:us-east-1:702902267788:secret:foo-bar5-Robbgh"
  1527. defaultVersion := "00000000-0000-0000-0000-000000000002"
  1528. secretValueOutput := &awssm.GetSecretValueOutput{
  1529. ARN: &arn,
  1530. VersionId: &defaultVersion,
  1531. }
  1532. blankSecretValueOutput := &awssm.GetSecretValueOutput{}
  1533. getSecretCorrectErr := types.ResourceNotFoundException{}
  1534. getSecretWrongErr := types.InvalidRequestException{}
  1535. pushSecretDataWithoutProperty := fake.PushSecretData{SecretKey: "fake-secret-key", RemoteKey: fakeKey, Property: ""}
  1536. type args struct {
  1537. store *esv1.AWSProvider
  1538. client fakesm.Client
  1539. pushSecretData fake.PushSecretData
  1540. }
  1541. type want struct {
  1542. err error
  1543. wantError bool
  1544. }
  1545. tests := map[string]struct {
  1546. args args
  1547. want want
  1548. }{
  1549. "SecretExistsReturnsTrueForExistingSecret": {
  1550. args: args{
  1551. store: makeValidSecretStore().Spec.Provider.AWS,
  1552. client: fakesm.Client{
  1553. GetSecretValueFn: fakesm.NewGetSecretValueFn(secretValueOutput, nil),
  1554. },
  1555. pushSecretData: pushSecretDataWithoutProperty,
  1556. },
  1557. want: want{
  1558. err: nil,
  1559. wantError: true,
  1560. },
  1561. },
  1562. "SecretExistsReturnsFalseForNonExistingSecret": {
  1563. args: args{
  1564. store: makeValidSecretStore().Spec.Provider.AWS,
  1565. client: fakesm.Client{
  1566. GetSecretValueFn: fakesm.NewGetSecretValueFn(blankSecretValueOutput, &getSecretCorrectErr),
  1567. },
  1568. pushSecretData: pushSecretDataWithoutProperty,
  1569. },
  1570. want: want{
  1571. err: nil,
  1572. wantError: false,
  1573. },
  1574. },
  1575. "SecretExistsReturnsFalseForErroredSecret": {
  1576. args: args{
  1577. store: makeValidSecretStore().Spec.Provider.AWS,
  1578. client: fakesm.Client{
  1579. GetSecretValueFn: fakesm.NewGetSecretValueFn(blankSecretValueOutput, &getSecretWrongErr),
  1580. },
  1581. pushSecretData: pushSecretDataWithoutProperty,
  1582. },
  1583. want: want{
  1584. err: &getSecretWrongErr,
  1585. wantError: false,
  1586. },
  1587. },
  1588. }
  1589. for name, tc := range tests {
  1590. t.Run(name, func(t *testing.T) {
  1591. sm := &SecretsManager{
  1592. client: &tc.args.client,
  1593. }
  1594. got, err := sm.SecretExists(context.Background(), tc.args.pushSecretData)
  1595. assert.Equal(
  1596. t,
  1597. tc.want,
  1598. want{
  1599. err: err,
  1600. wantError: got,
  1601. })
  1602. })
  1603. }
  1604. }
  1605. func TestConstructMetadataWithDefaults(t *testing.T) {
  1606. tests := []struct {
  1607. name string
  1608. input *apiextensionsv1.JSON
  1609. expected *metadata.PushSecretMetadata[PushSecretMetadataSpec]
  1610. expectError bool
  1611. }{
  1612. {
  1613. name: "Valid metadata with multiple fields",
  1614. input: &apiextensionsv1.JSON{Raw: []byte(`{
  1615. "apiVersion": "kubernetes.external-secrets.io/v1alpha1",
  1616. "kind": "PushSecretMetadata",
  1617. "spec": {
  1618. "description": "test description",
  1619. "secretPushFormat":"string",
  1620. "kmsKeyID": "custom-kms-key",
  1621. "tags": {
  1622. "customKey": "customValue"
  1623. },
  1624. }
  1625. }`)},
  1626. expected: &metadata.PushSecretMetadata[PushSecretMetadataSpec]{
  1627. APIVersion: "kubernetes.external-secrets.io/v1alpha1",
  1628. Kind: "PushSecretMetadata",
  1629. Spec: PushSecretMetadataSpec{
  1630. Description: "test description",
  1631. SecretPushFormat: "string",
  1632. KMSKeyID: "custom-kms-key",
  1633. Tags: map[string]string{
  1634. "customKey": "customValue",
  1635. managedBy: externalSecrets,
  1636. },
  1637. },
  1638. },
  1639. },
  1640. {
  1641. name: "Empty metadata, defaults applied",
  1642. input: nil,
  1643. expected: &metadata.PushSecretMetadata[PushSecretMetadataSpec]{
  1644. Spec: PushSecretMetadataSpec{
  1645. Description: fmt.Sprintf("secret '%s:%s'", managedBy, externalSecrets),
  1646. SecretPushFormat: "binary",
  1647. KMSKeyID: "alias/aws/secretsmanager",
  1648. Tags: map[string]string{
  1649. managedBy: externalSecrets,
  1650. },
  1651. },
  1652. },
  1653. },
  1654. {
  1655. name: "Added default metadata with 'managed-by' tag",
  1656. input: &apiextensionsv1.JSON{Raw: []byte(`{
  1657. "apiVersion": "kubernetes.external-secrets.io/v1alpha1",
  1658. "kind": "PushSecretMetadata",
  1659. "spec": {
  1660. "tags": {
  1661. "managed-by": "external-secrets",
  1662. "customKey": "customValue"
  1663. },
  1664. }
  1665. }`)},
  1666. expected: nil,
  1667. expectError: true,
  1668. },
  1669. {
  1670. name: "Invalid metadata format",
  1671. input: &apiextensionsv1.JSON{Raw: []byte(`invalid-json`)},
  1672. expected: nil,
  1673. expectError: true,
  1674. },
  1675. {
  1676. name: "Metadata with 'managed-by' tag specified",
  1677. input: &apiextensionsv1.JSON{Raw: []byte(`{"tags":{"managed-by":"invalid"}}`)},
  1678. expected: nil,
  1679. expectError: true,
  1680. },
  1681. }
  1682. for _, tt := range tests {
  1683. t.Run(tt.name, func(t *testing.T) {
  1684. result, err := (&SecretsManager{}).constructMetadataWithDefaults(tt.input)
  1685. if tt.expectError {
  1686. assert.Error(t, err)
  1687. } else {
  1688. assert.NoError(t, err)
  1689. assert.Equal(t, tt.expected, result)
  1690. }
  1691. })
  1692. }
  1693. }
  1694. func TestComputeTagsToUpdate(t *testing.T) {
  1695. tests := []struct {
  1696. name string
  1697. tags map[string]string
  1698. metaTags map[string]string
  1699. expected []types.Tag
  1700. modified bool
  1701. }{
  1702. {
  1703. name: "No tags to update",
  1704. tags: map[string]string{
  1705. "key1": "value1",
  1706. "key2": "value2",
  1707. },
  1708. metaTags: map[string]string{
  1709. "key1": "value1",
  1710. "key2": "value2",
  1711. },
  1712. expected: []types.Tag{
  1713. {Key: ptr.To("key1"), Value: ptr.To("value1")},
  1714. {Key: ptr.To("key2"), Value: ptr.To("value2")},
  1715. },
  1716. modified: false,
  1717. },
  1718. {
  1719. name: "No tags to update as managed-by tag is ignored",
  1720. tags: map[string]string{
  1721. "key1": "value1",
  1722. "key2": "value2",
  1723. },
  1724. metaTags: map[string]string{
  1725. "key1": "value1",
  1726. "key2": "value2",
  1727. managedBy: externalSecrets,
  1728. },
  1729. expected: []types.Tag{
  1730. {Key: ptr.To("key1"), Value: ptr.To("value1")},
  1731. {Key: ptr.To("key2"), Value: ptr.To("value2")},
  1732. {Key: ptr.To(managedBy), Value: ptr.To(externalSecrets)},
  1733. },
  1734. modified: false,
  1735. },
  1736. {
  1737. name: "Add new tag",
  1738. tags: map[string]string{
  1739. "key1": "value1",
  1740. },
  1741. metaTags: map[string]string{
  1742. "key1": "value1",
  1743. "key2": "value2",
  1744. },
  1745. expected: []types.Tag{
  1746. {Key: ptr.To("key1"), Value: ptr.To("value1")},
  1747. {Key: ptr.To("key2"), Value: ptr.To("value2")},
  1748. },
  1749. modified: true,
  1750. },
  1751. {
  1752. name: "Update existing tag value",
  1753. tags: map[string]string{
  1754. "key1": "value1",
  1755. },
  1756. metaTags: map[string]string{
  1757. "key1": "newValue",
  1758. },
  1759. expected: []types.Tag{
  1760. {Key: ptr.To("key1"), Value: ptr.To("newValue")},
  1761. },
  1762. modified: true,
  1763. },
  1764. {
  1765. name: "Empty tags and metaTags",
  1766. tags: map[string]string{},
  1767. metaTags: map[string]string{},
  1768. expected: []types.Tag{},
  1769. modified: false,
  1770. },
  1771. {
  1772. name: "Empty tags with non-empty metaTags",
  1773. tags: map[string]string{},
  1774. metaTags: map[string]string{
  1775. "key1": "value1",
  1776. },
  1777. expected: []types.Tag{
  1778. {Key: ptr.To("key1"), Value: ptr.To("value1")},
  1779. },
  1780. modified: true,
  1781. },
  1782. }
  1783. for _, tt := range tests {
  1784. t.Run(tt.name, func(t *testing.T) {
  1785. result, modified := computeTagsToUpdate(tt.tags, tt.metaTags)
  1786. assert.ElementsMatch(t, tt.expected, result)
  1787. assert.Equal(t, tt.modified, modified)
  1788. })
  1789. }
  1790. }
  1791. func TestPatchTags(t *testing.T) {
  1792. type call struct {
  1793. untagCalled bool
  1794. tagCalled bool
  1795. }
  1796. tests := []struct {
  1797. name string
  1798. existingTags map[string]string
  1799. metaTags map[string]string
  1800. expectUntag bool
  1801. expectTag bool
  1802. assertsTag func(input *awssm.TagResourceInput)
  1803. assertsUntag func(input *awssm.UntagResourceInput)
  1804. }{
  1805. {
  1806. name: "no changes",
  1807. existingTags: map[string]string{"a": "1"},
  1808. metaTags: map[string]string{"a": "1"},
  1809. expectUntag: false,
  1810. expectTag: false,
  1811. assertsTag: func(input *awssm.TagResourceInput) {
  1812. assert.Fail(t, "Expected TagResource to not be called")
  1813. },
  1814. assertsUntag: func(input *awssm.UntagResourceInput) {
  1815. assert.Fail(t, "Expected UntagResource to not be called")
  1816. },
  1817. },
  1818. {
  1819. name: "update tag value",
  1820. existingTags: map[string]string{"a": "1"},
  1821. metaTags: map[string]string{"a": "2"},
  1822. expectUntag: false,
  1823. expectTag: true,
  1824. assertsTag: func(input *awssm.TagResourceInput) {
  1825. assert.Contains(t, input.Tags, types.Tag{Key: ptr.To(managedBy), Value: ptr.To(externalSecrets)})
  1826. assert.Contains(t, input.Tags, types.Tag{Key: ptr.To("a"), Value: ptr.To("2")})
  1827. },
  1828. assertsUntag: func(input *awssm.UntagResourceInput) {
  1829. assert.Fail(t, "Expected UntagResource to not be called")
  1830. },
  1831. },
  1832. {
  1833. name: "remove tag",
  1834. existingTags: map[string]string{"a": "1", "b": "2"},
  1835. metaTags: map[string]string{"a": "1"},
  1836. expectUntag: true,
  1837. expectTag: false,
  1838. assertsTag: func(input *awssm.TagResourceInput) {
  1839. assert.Fail(t, "Expected TagResource to not be called")
  1840. },
  1841. assertsUntag: func(input *awssm.UntagResourceInput) {
  1842. assert.Equal(t, []string{"b"}, input.TagKeys)
  1843. },
  1844. },
  1845. {
  1846. name: "add tags",
  1847. existingTags: map[string]string{"a": "1"},
  1848. metaTags: map[string]string{"a": "1", "b": "2"},
  1849. expectUntag: false,
  1850. expectTag: true,
  1851. assertsTag: func(input *awssm.TagResourceInput) {
  1852. assert.Contains(t, input.Tags, types.Tag{Key: ptr.To(managedBy), Value: ptr.To(externalSecrets)})
  1853. assert.Contains(t, input.Tags, types.Tag{Key: ptr.To("a"), Value: ptr.To("1")})
  1854. assert.Contains(t, input.Tags, types.Tag{Key: ptr.To("b"), Value: ptr.To("2")})
  1855. },
  1856. assertsUntag: func(input *awssm.UntagResourceInput) {
  1857. assert.Fail(t, "Expected UntagResource to not be called")
  1858. },
  1859. },
  1860. }
  1861. for _, tt := range tests {
  1862. t.Run(tt.name, func(t *testing.T) {
  1863. calls := call{}
  1864. fakeClient := &fakesm.Client{
  1865. TagResourceFn: fakesm.NewTagResourceFn(&awssm.TagResourceOutput{}, nil, func(input *awssm.TagResourceInput) {
  1866. tt.assertsTag(input)
  1867. calls.tagCalled = true
  1868. }),
  1869. UntagResourceFn: fakesm.NewUntagResourceFn(&awssm.UntagResourceOutput{}, nil, func(input *awssm.UntagResourceInput) {
  1870. tt.assertsUntag(input)
  1871. calls.untagCalled = true
  1872. }),
  1873. }
  1874. sm := &SecretsManager{client: fakeClient}
  1875. metaMap := map[string]interface{}{
  1876. "apiVersion": "kubernetes.external-secrets.io/v1alpha1",
  1877. "kind": "PushSecretMetadata",
  1878. "spec": map[string]interface{}{
  1879. "description": "adding managed-by tag explicitly",
  1880. "tags": tt.metaTags,
  1881. },
  1882. }
  1883. raw, err := json.Marshal(metaMap)
  1884. require.NoError(t, err)
  1885. meta := &apiextensionsv1.JSON{Raw: raw}
  1886. secretId := "secret"
  1887. err = sm.patchTags(context.Background(), meta, &secretId, tt.existingTags)
  1888. require.NoError(t, err)
  1889. assert.Equal(t, tt.expectUntag, calls.untagCalled)
  1890. assert.Equal(t, tt.expectTag, calls.tagCalled)
  1891. })
  1892. }
  1893. }
  1894. // FakeCredProvider implements the AWS credentials.Provider interface
  1895. // It is used to inject an error into the AWS config to cause a
  1896. // validation error.
  1897. type FakeCredProvider struct {
  1898. retrieveFunc func() (aws.Credentials, error)
  1899. }
  1900. func (f *FakeCredProvider) Retrieve(ctx context.Context) (aws.Credentials, error) {
  1901. return f.retrieveFunc()
  1902. }
  1903. func (f *FakeCredProvider) IsExpired() bool {
  1904. return true
  1905. }