secretsmanager_test.go 75 KB

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