secretsmanager_test.go 81 KB

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