| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481 |
- /*
- Copyright © The ESO Authors
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
- https://www.apache.org/licenses/LICENSE-2.0
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- */
- package secretsmanager
- import (
- "context"
- "encoding/json"
- "errors"
- "fmt"
- "reflect"
- "strings"
- "testing"
- "time"
- "github.com/aws/aws-sdk-go-v2/aws"
- "github.com/aws/aws-sdk-go-v2/credentials"
- awssm "github.com/aws/aws-sdk-go-v2/service/secretsmanager"
- "github.com/aws/aws-sdk-go-v2/service/secretsmanager/types"
- "github.com/google/go-cmp/cmp"
- "github.com/stretchr/testify/assert"
- "github.com/stretchr/testify/require"
- corev1 "k8s.io/api/core/v1"
- apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
- "sigs.k8s.io/controller-runtime/pkg/client"
- clientfake "sigs.k8s.io/controller-runtime/pkg/client/fake"
- esv1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1"
- fakesm "github.com/external-secrets/external-secrets/providers/v1/aws/secretsmanager/fake"
- awsutil "github.com/external-secrets/external-secrets/providers/v1/aws/util"
- "github.com/external-secrets/external-secrets/runtime/esutils/metadata"
- "github.com/external-secrets/external-secrets/runtime/testing/fake"
- )
- const (
- testARN = "arn:aws:secretsmanager:us-east-1:702902267788:secret:foo-bar5-Robbgh"
- testDefaultVersion = "00000000-0000-0000-0000-000000000002"
- )
- type secretsManagerTestCase struct {
- fakeClient *fakesm.Client
- apiInput *awssm.GetSecretValueInput
- apiOutput *awssm.GetSecretValueOutput
- remoteRef *esv1.ExternalSecretDataRemoteRef
- apiErr error
- expectError string
- expectedSecret string
- // for testing secretmap
- expectedData map[string][]byte
- // for testing caching
- expectedCounter *int
- prefix string
- }
- const unexpectedErrorString = "[%d] unexpected error: %s, expected: '%s'"
- const (
- tagname1 = "tagname1"
- tagvalue1 = "tagvalue1"
- tagname2 = "tagname2"
- tagvalue2 = "tagvalue2"
- fakeKey = "fake-key"
- fakeSecretKey = "fake-secret-key"
- )
- func makeValidSecretsManagerTestCase() *secretsManagerTestCase {
- smtc := secretsManagerTestCase{
- fakeClient: fakesm.NewClient(),
- apiInput: makeValidAPIInput(),
- remoteRef: makeValidRemoteRef(),
- apiOutput: makeValidAPIOutput(),
- apiErr: nil,
- expectError: "",
- expectedSecret: "",
- expectedData: map[string][]byte{},
- }
- smtc.fakeClient.WithValue(smtc.apiInput, smtc.apiOutput, smtc.apiErr)
- return &smtc
- }
- func makeValidRemoteRef() *esv1.ExternalSecretDataRemoteRef {
- return &esv1.ExternalSecretDataRemoteRef{
- Key: "/baz",
- Version: "AWSCURRENT",
- }
- }
- func makeValidAPIInput() *awssm.GetSecretValueInput {
- return &awssm.GetSecretValueInput{
- SecretId: aws.String("/baz"),
- VersionStage: aws.String("AWSCURRENT"),
- }
- }
- func makeValidAPIOutput() *awssm.GetSecretValueOutput {
- return &awssm.GetSecretValueOutput{
- SecretString: aws.String(""),
- }
- }
- func makeValidGetResourcePolicyOutput() *awssm.GetResourcePolicyOutput {
- return &awssm.GetResourcePolicyOutput{
- ResourcePolicy: aws.String(`{
- "Version": "2012-10-17",
- "Statement": [
- {
- "Sid": "DenyPolicyChangesExceptAdmins",
- "Effect": "Deny",
- "Principal": "*",
- "Action": [
- "secretsmanager:PutResourcePolicy",
- "secretsmanager:DeleteResourcePolicy",
- "secretsmanager:GetResourcePolicy"
- ],
- "Resource": "*",
- "Condition": {
- "ArnNotEquals": {
- "aws:PrincipalArn": [
- "arn:aws:iam::000000000000:root",
- "arn:aws:iam::000000000000:role/admin"
- ]
- }
- }
- }
- ]
- }`),
- }
- }
- func makeValidSecretsManagerTestCaseCustom(tweaks ...func(smtc *secretsManagerTestCase)) *secretsManagerTestCase {
- smtc := makeValidSecretsManagerTestCase()
- for _, fn := range tweaks {
- fn(smtc)
- }
- smtc.fakeClient.WithValue(smtc.apiInput, smtc.apiOutput, smtc.apiErr)
- return smtc
- }
- // This case can be shared by both GetSecret and GetSecretMap tests.
- // bad case: set apiErr.
- var setAPIErr = func(smtc *secretsManagerTestCase) {
- smtc.apiErr = errors.New("oh no")
- smtc.expectError = "oh no"
- }
- func TestSecretsManagerResolver(t *testing.T) {
- endpointEnvKey := SecretsManagerEndpointEnv
- endpointURL := "http://sm.foo"
- t.Setenv(endpointEnvKey, endpointURL)
- f, err := customEndpointResolver{}.ResolveEndpoint(context.Background(), awssm.EndpointParameters{})
- assert.Nil(t, err)
- assert.Equal(t, endpointURL, f.URI.String())
- }
- // test the sm<->aws interface
- // make sure correct values are passed and errors are handled accordingly.
- func TestSecretsManagerGetSecret(t *testing.T) {
- // good case: default version is set
- // key is passed in, output is sent back
- setSecretString := func(smtc *secretsManagerTestCase) {
- smtc.apiOutput.SecretString = aws.String("testtesttest")
- smtc.expectedSecret = "testtesttest"
- }
- // good case: key is passed in with prefix
- setSecretStringWithPrefix := func(smtc *secretsManagerTestCase) {
- smtc.remoteRef.Key = "secret-key"
- smtc.apiInput = &awssm.GetSecretValueInput{
- SecretId: aws.String("my-prefix/secret-key"),
- VersionStage: aws.String("AWSCURRENT"),
- }
- smtc.prefix = "my-prefix/"
- }
- // good case: extract property
- // Testing that the property exists in the SecretString
- setRemoteRefPropertyExistsInKey := func(smtc *secretsManagerTestCase) {
- smtc.remoteRef.Property = "/shmoo"
- smtc.apiOutput.SecretString = aws.String(`{"/shmoo": "bang"}`)
- smtc.expectedSecret = "bang"
- }
- // bad case: missing property
- setRemoteRefMissingProperty := func(smtc *secretsManagerTestCase) {
- smtc.remoteRef.Property = "INVALPROP"
- smtc.expectError = "key INVALPROP does not exist in secret"
- }
- // bad case: extract property failure due to invalid json
- setRemoteRefMissingPropertyInvalidJSON := func(smtc *secretsManagerTestCase) {
- smtc.remoteRef.Property = "INVALPROP"
- smtc.apiOutput.SecretString = aws.String(`------`)
- smtc.expectError = "key INVALPROP does not exist in secret"
- }
- // good case: set .SecretString to nil but set binary with value
- setSecretBinaryNotSecretString := func(smtc *secretsManagerTestCase) {
- smtc.apiOutput.SecretBinary = []byte("yesplease")
- // needs to be set as nil, empty quotes ("") is considered existing
- smtc.apiOutput.SecretString = nil
- smtc.expectedSecret = "yesplease"
- }
- // bad case: both .SecretString and .SecretBinary are nil
- setSecretBinaryAndSecretStringToNil := func(smtc *secretsManagerTestCase) {
- smtc.apiOutput.SecretBinary = nil
- smtc.apiOutput.SecretString = nil
- smtc.expectError = "no secret string nor binary for key"
- }
- // good case: secretOut.SecretBinary JSON parsing
- setNestedSecretValueJSONParsing := func(smtc *secretsManagerTestCase) {
- smtc.apiOutput.SecretString = nil
- smtc.apiOutput.SecretBinary = []byte(`{"foobar":{"baz":"nestedval"}}`)
- smtc.remoteRef.Property = "foobar.baz"
- smtc.expectedSecret = "nestedval"
- }
- // good case: secretOut.SecretBinary no JSON parsing if name on key
- setSecretValueWithDot := func(smtc *secretsManagerTestCase) {
- smtc.apiOutput.SecretString = nil
- smtc.apiOutput.SecretBinary = []byte(`{"foobar.baz":"nestedval"}`)
- smtc.remoteRef.Property = "foobar.baz"
- smtc.expectedSecret = "nestedval"
- }
- // good case: custom version stage set
- setCustomVersionStage := func(smtc *secretsManagerTestCase) {
- smtc.apiInput.VersionStage = aws.String("1234")
- smtc.remoteRef.Version = "1234"
- smtc.apiOutput.SecretString = aws.String("FOOBA!")
- smtc.expectedSecret = "FOOBA!"
- }
- // good case: custom version id set
- setCustomVersionID := func(smtc *secretsManagerTestCase) {
- smtc.apiInput.VersionStage = nil
- smtc.apiInput.VersionId = aws.String("1234-5678")
- smtc.remoteRef.Version = "uuid/1234-5678"
- smtc.apiOutput.SecretString = aws.String("myvalue")
- smtc.expectedSecret = "myvalue"
- }
- fetchMetadata := func(smtc *secretsManagerTestCase) {
- smtc.remoteRef.MetadataPolicy = esv1.ExternalSecretMetadataPolicyFetch
- describeSecretOutput := &awssm.DescribeSecretOutput{
- Tags: getTagSlice(),
- }
- smtc.fakeClient.DescribeSecretFn = fakesm.NewDescribeSecretFn(describeSecretOutput, nil)
- jsonTags, _ := awsutil.SecretTagsToJSONString(getTagSlice())
- smtc.apiOutput.SecretString = &jsonTags
- smtc.expectedSecret = jsonTags
- }
- fetchMetadataProperty := func(smtc *secretsManagerTestCase) {
- smtc.remoteRef.MetadataPolicy = esv1.ExternalSecretMetadataPolicyFetch
- describeSecretOutput := &awssm.DescribeSecretOutput{
- Tags: getTagSlice(),
- }
- smtc.fakeClient.DescribeSecretFn = fakesm.NewDescribeSecretFn(describeSecretOutput, nil)
- smtc.remoteRef.Property = tagname2
- jsonTags, _ := awsutil.SecretTagsToJSONString(getTagSlice())
- smtc.apiOutput.SecretString = &jsonTags
- smtc.expectedSecret = tagvalue2
- }
- failMetadataWrongProperty := func(smtc *secretsManagerTestCase) {
- smtc.remoteRef.MetadataPolicy = esv1.ExternalSecretMetadataPolicyFetch
- describeSecretOutput := &awssm.DescribeSecretOutput{
- Tags: getTagSlice(),
- }
- smtc.fakeClient.DescribeSecretFn = fakesm.NewDescribeSecretFn(describeSecretOutput, nil)
- smtc.remoteRef.Property = "fail"
- jsonTags, _ := awsutil.SecretTagsToJSONString(getTagSlice())
- smtc.apiOutput.SecretString = &jsonTags
- smtc.expectError = "key fail does not exist in secret /baz"
- }
- successCases := []*secretsManagerTestCase{
- makeValidSecretsManagerTestCase(),
- makeValidSecretsManagerTestCaseCustom(setSecretString),
- makeValidSecretsManagerTestCaseCustom(setSecretStringWithPrefix),
- makeValidSecretsManagerTestCaseCustom(setRemoteRefPropertyExistsInKey),
- makeValidSecretsManagerTestCaseCustom(setRemoteRefMissingProperty),
- makeValidSecretsManagerTestCaseCustom(setRemoteRefMissingPropertyInvalidJSON),
- makeValidSecretsManagerTestCaseCustom(setSecretBinaryNotSecretString),
- makeValidSecretsManagerTestCaseCustom(setSecretBinaryAndSecretStringToNil),
- makeValidSecretsManagerTestCaseCustom(setNestedSecretValueJSONParsing),
- makeValidSecretsManagerTestCaseCustom(setSecretValueWithDot),
- makeValidSecretsManagerTestCaseCustom(setCustomVersionStage),
- makeValidSecretsManagerTestCaseCustom(setCustomVersionID),
- makeValidSecretsManagerTestCaseCustom(setAPIErr),
- makeValidSecretsManagerTestCaseCustom(fetchMetadata),
- makeValidSecretsManagerTestCaseCustom(fetchMetadataProperty),
- makeValidSecretsManagerTestCaseCustom(failMetadataWrongProperty),
- }
- for k, v := range successCases {
- sm := SecretsManager{
- cache: make(map[string]*awssm.GetSecretValueOutput),
- client: v.fakeClient,
- prefix: v.prefix,
- }
- out, err := sm.GetSecret(context.Background(), *v.remoteRef)
- if !ErrorContains(err, v.expectError) {
- t.Errorf(unexpectedErrorString, k, err.Error(), v.expectError)
- }
- if err == nil && string(out) != v.expectedSecret {
- t.Errorf("[%d] unexpected secret: expected %s, got %s", k, v.expectedSecret, string(out))
- }
- }
- }
- func TestCaching(t *testing.T) {
- fakeClient := fakesm.NewClient()
- // good case: first call, since we are using the same key, results should be cached and the counter should not go
- // over 1
- firstCall := func(smtc *secretsManagerTestCase) {
- smtc.apiOutput.SecretString = aws.String(`{"foo":"bar", "bar":"vodka"}`)
- smtc.remoteRef.Property = "foo"
- smtc.expectedSecret = "bar"
- smtc.expectedCounter = aws.Int(1)
- smtc.fakeClient = fakeClient
- }
- secondCall := func(smtc *secretsManagerTestCase) {
- smtc.apiOutput.SecretString = aws.String(`{"foo":"bar", "bar":"vodka"}`)
- smtc.remoteRef.Property = "bar"
- smtc.expectedSecret = "vodka"
- smtc.expectedCounter = aws.Int(1)
- smtc.fakeClient = fakeClient
- }
- notCachedCall := func(smtc *secretsManagerTestCase) {
- smtc.apiOutput.SecretString = aws.String(`{"sheldon":"bazinga", "bar":"foo"}`)
- smtc.remoteRef.Property = "sheldon"
- smtc.expectedSecret = "bazinga"
- smtc.expectedCounter = aws.Int(2)
- smtc.fakeClient = fakeClient
- smtc.apiInput.SecretId = aws.String("xyz")
- smtc.remoteRef.Key = "xyz" // it should reset the cache since the key is different
- }
- cachedCases := []*secretsManagerTestCase{
- makeValidSecretsManagerTestCaseCustom(firstCall),
- makeValidSecretsManagerTestCaseCustom(firstCall),
- makeValidSecretsManagerTestCaseCustom(secondCall),
- makeValidSecretsManagerTestCaseCustom(notCachedCall),
- }
- sm := SecretsManager{
- cache: make(map[string]*awssm.GetSecretValueOutput),
- }
- for k, v := range cachedCases {
- sm.client = v.fakeClient
- out, err := sm.GetSecret(context.Background(), *v.remoteRef)
- if !ErrorContains(err, v.expectError) {
- t.Errorf(unexpectedErrorString, k, err.Error(), v.expectError)
- }
- if err == nil && string(out) != v.expectedSecret {
- t.Errorf("[%d] unexpected secret: expected %s, got %s", k, v.expectedSecret, string(out))
- }
- if v.expectedCounter != nil && v.fakeClient.ExecutionCounter != *v.expectedCounter {
- t.Errorf("[%d] unexpected counter value: expected %d, got %d", k, v.expectedCounter, v.fakeClient.ExecutionCounter)
- }
- }
- }
- func TestGetSecretMap(t *testing.T) {
- // good case: default version & deserialization
- setDeserialization := func(smtc *secretsManagerTestCase) {
- smtc.apiOutput.SecretString = aws.String(`{"foo":"bar"}`)
- smtc.expectedData["foo"] = []byte("bar")
- }
- // good case: nested json
- setNestedJSON := func(smtc *secretsManagerTestCase) {
- smtc.apiOutput.SecretString = aws.String(`{"foobar":{"baz":"nestedval"}}`)
- smtc.expectedData["foobar"] = []byte("{\"baz\":\"nestedval\"}")
- }
- // good case: caching
- cachedMap := func(smtc *secretsManagerTestCase) {
- smtc.apiOutput.SecretString = aws.String(`{"foo":"bar", "plus": "one"}`)
- smtc.expectedData["foo"] = []byte("bar")
- smtc.expectedData["plus"] = []byte("one")
- smtc.expectedCounter = aws.Int(1)
- }
- // bad case: invalid json
- setInvalidJSON := func(smtc *secretsManagerTestCase) {
- smtc.apiOutput.SecretString = aws.String(`-----------------`)
- smtc.expectError = "unable to unmarshal secret"
- }
- successCases := []*secretsManagerTestCase{
- makeValidSecretsManagerTestCaseCustom(setDeserialization),
- makeValidSecretsManagerTestCaseCustom(setNestedJSON),
- makeValidSecretsManagerTestCaseCustom(setAPIErr),
- makeValidSecretsManagerTestCaseCustom(setInvalidJSON),
- makeValidSecretsManagerTestCaseCustom(cachedMap),
- }
- for k, v := range successCases {
- sm := SecretsManager{
- cache: make(map[string]*awssm.GetSecretValueOutput),
- client: v.fakeClient,
- }
- out, err := sm.GetSecretMap(context.Background(), *v.remoteRef)
- if !ErrorContains(err, v.expectError) {
- t.Errorf(unexpectedErrorString, k, err.Error(), v.expectError)
- }
- if err == nil && !cmp.Equal(out, v.expectedData) {
- t.Errorf("[%d] unexpected secret data: expected %#v, got %#v", k, v.expectedData, out)
- }
- if v.expectedCounter != nil && v.fakeClient.ExecutionCounter != *v.expectedCounter {
- t.Errorf("[%d] unexpected counter value: expected %d, got %d", k, v.expectedCounter, v.fakeClient.ExecutionCounter)
- }
- }
- }
- func ErrorContains(out error, want string) bool {
- if out == nil {
- return want == ""
- }
- if want == "" {
- return false
- }
- return strings.Contains(out.Error(), want)
- }
- func TestSetSecret(t *testing.T) {
- managedBy := managedBy
- notManagedBy := "not-managed-by"
- secretKey := fakeSecretKey
- secretValue := []byte("fake-value")
- fakeSecret := &corev1.Secret{
- Data: map[string][]byte{
- secretKey: secretValue,
- },
- }
- externalSecrets := externalSecrets
- noPermission := errors.New("no permission")
- arn := testARN
- getSecretCorrectErr := types.ResourceNotFoundException{}
- getSecretWrongErr := types.InvalidRequestException{}
- secretOutput := &awssm.CreateSecretOutput{
- ARN: &arn,
- }
- externalSecretsTag := []types.Tag{
- {
- Key: &managedBy,
- Value: &externalSecrets,
- },
- {
- Key: new("taname1"),
- Value: new("tagvalue1"),
- },
- }
- externalSecretsTagFaulty := []types.Tag{
- {
- Key: ¬ManagedBy,
- Value: &externalSecrets,
- },
- }
- tagSecretOutputNoVersions := &awssm.DescribeSecretOutput{
- ARN: &arn,
- Tags: externalSecretsTag,
- }
- defaultVersion := testDefaultVersion
- tagSecretOutput := &awssm.DescribeSecretOutput{
- ARN: &arn,
- Tags: externalSecretsTag,
- VersionIdsToStages: map[string][]string{
- defaultVersion: {"AWSCURRENT"},
- },
- }
- tagSecretOutputFaulty := &awssm.DescribeSecretOutput{
- ARN: &arn,
- Tags: externalSecretsTagFaulty,
- }
- tagSecretOutputFrom := func(versionId string) *awssm.DescribeSecretOutput {
- return &awssm.DescribeSecretOutput{
- ARN: &arn,
- Tags: externalSecretsTag,
- VersionIdsToStages: map[string][]string{
- versionId: {"AWSCURRENT"},
- },
- }
- }
- initialVersion := "00000000-0000-0000-0000-000000000001"
- defaultUpdatedVersion := "6c70d57a-f53d-bf4d-9525-3503dd5abe8c"
- randomUUIDVersion := "9d6202c2-c216-433e-a2f0-5836c4f025af"
- randomUUIDVersionIncremented := "4346824b-7da1-4d82-addf-dee197fd5d71"
- unparsableVersion := "IAM UNPARSABLE"
- secretValueOutput := &awssm.GetSecretValueOutput{
- ARN: &arn,
- VersionId: &defaultVersion,
- }
- secretValueOutput2 := &awssm.GetSecretValueOutput{
- ARN: &arn,
- SecretBinary: secretValue,
- VersionId: &defaultVersion,
- }
- blankDescribeSecretOutput := &awssm.DescribeSecretOutput{}
- type params struct {
- s string
- b []byte
- version *string
- }
- secretValueOutputFrom := func(params params) *awssm.GetSecretValueOutput {
- var version *string
- if params.version == nil {
- version = &defaultVersion
- } else {
- version = params.version
- }
- return &awssm.GetSecretValueOutput{
- ARN: &arn,
- SecretString: ¶ms.s,
- SecretBinary: params.b,
- VersionId: version,
- }
- }
- putSecretOutput := &awssm.PutSecretValueOutput{
- ARN: &arn,
- }
- pushSecretDataWithoutProperty := fake.PushSecretData{SecretKey: secretKey, RemoteKey: fakeKey, Property: ""}
- pushSecretDataWithoutSecretKey := fake.PushSecretData{RemoteKey: fakeKey, Property: ""}
- pushSecretDataWithMetadata := fake.PushSecretData{SecretKey: secretKey, RemoteKey: fakeKey, Property: "", Metadata: &apiextensionsv1.JSON{
- Raw: []byte(`{
- "apiVersion": "kubernetes.external-secrets.io/v1alpha1",
- "kind": "PushSecretMetadata",
- "spec": {
- "secretPushFormat": "string"
- }
- }`)}}
- pushSecretDataWithProperty := fake.PushSecretData{SecretKey: secretKey, RemoteKey: fakeKey, Property: "other-fake-property"}
- type args struct {
- store *esv1.AWSProvider
- client fakesm.Client
- pushSecretData fake.PushSecretData
- newUUID string
- kubeclient client.Client
- }
- type want struct {
- err error
- }
- tests := map[string]struct {
- reason string
- args args
- want want
- }{
- "SetSecretSucceedsWithExistingSecret": {
- reason: "a secret can be pushed to aws secrets manager when it already exists",
- args: args{
- store: makeValidSecretStore().Spec.Provider.AWS,
- client: fakesm.Client{
- GetSecretValueFn: fakesm.NewGetSecretValueFn(secretValueOutput, nil),
- PutSecretValueFn: fakesm.NewPutSecretValueFn(putSecretOutput, nil),
- DescribeSecretFn: fakesm.NewDescribeSecretFn(tagSecretOutput, nil),
- TagResourceFn: fakesm.NewTagResourceFn(&awssm.TagResourceOutput{}, nil),
- UntagResourceFn: fakesm.NewUntagResourceFn(&awssm.UntagResourceOutput{}, nil),
- DeleteResourcePolicyFn: fakesm.NewDeleteResourcePolicyFn(&awssm.DeleteResourcePolicyOutput{}, nil),
- },
- pushSecretData: pushSecretDataWithoutProperty,
- },
- want: want{
- err: nil,
- },
- },
- "SetSecretSucceedsWithExistingSecretButNoSecretVersionsWithoutProperty": {
- reason: "a secret can be pushed to aws secrets manager when it already exists but has no secret versions",
- args: args{
- store: makeValidSecretStore().Spec.Provider.AWS,
- client: fakesm.Client{
- DescribeSecretFn: fakesm.NewDescribeSecretFn(tagSecretOutputNoVersions, nil),
- PutSecretValueFn: fakesm.NewPutSecretValueFn(putSecretOutput, nil, fakesm.ExpectedPutSecretValueInput{
- SecretBinary: []byte(`fake-value`),
- Version: aws.String(initialVersion),
- }),
- TagResourceFn: fakesm.NewTagResourceFn(&awssm.TagResourceOutput{}, nil),
- UntagResourceFn: fakesm.NewUntagResourceFn(&awssm.UntagResourceOutput{}, nil),
- DeleteResourcePolicyFn: fakesm.NewDeleteResourcePolicyFn(&awssm.DeleteResourcePolicyOutput{}, nil),
- },
- pushSecretData: pushSecretDataWithoutProperty,
- },
- want: want{
- err: nil,
- },
- },
- "SetSecretSucceedsWithExistingSecretButNoSecretVersionsWithProperty": {
- reason: "a secret can be pushed to aws secrets manager when it already exists but has no secret versions",
- args: args{
- store: makeValidSecretStore().Spec.Provider.AWS,
- client: fakesm.Client{
- DescribeSecretFn: fakesm.NewDescribeSecretFn(tagSecretOutputNoVersions, nil),
- PutSecretValueFn: fakesm.NewPutSecretValueFn(putSecretOutput, nil, fakesm.ExpectedPutSecretValueInput{
- SecretBinary: []byte(`{"other-fake-property":"fake-value"}`),
- Version: aws.String(initialVersion),
- }),
- TagResourceFn: fakesm.NewTagResourceFn(&awssm.TagResourceOutput{}, nil),
- UntagResourceFn: fakesm.NewUntagResourceFn(&awssm.UntagResourceOutput{}, nil),
- DeleteResourcePolicyFn: fakesm.NewDeleteResourcePolicyFn(&awssm.DeleteResourcePolicyOutput{}, nil),
- },
- pushSecretData: pushSecretDataWithProperty,
- },
- want: want{
- err: nil,
- },
- },
- "SetSecretSucceedsWithoutSecretKey": {
- reason: "a secret can be pushed to aws secrets manager without secret key",
- args: args{
- store: makeValidSecretStore().Spec.Provider.AWS,
- client: fakesm.Client{
- GetSecretValueFn: fakesm.NewGetSecretValueFn(secretValueOutput, nil),
- PutSecretValueFn: fakesm.NewPutSecretValueFn(putSecretOutput, nil),
- DescribeSecretFn: fakesm.NewDescribeSecretFn(tagSecretOutput, nil),
- TagResourceFn: fakesm.NewTagResourceFn(&awssm.TagResourceOutput{}, nil),
- UntagResourceFn: fakesm.NewUntagResourceFn(&awssm.UntagResourceOutput{}, nil),
- DeleteResourcePolicyFn: fakesm.NewDeleteResourcePolicyFn(&awssm.DeleteResourcePolicyOutput{}, nil),
- },
- pushSecretData: pushSecretDataWithoutSecretKey,
- },
- want: want{
- err: nil,
- },
- },
- "SetSecretSucceedsWithExistingSecretAndStringFormat": {
- reason: "a secret can be pushed to aws secrets manager when it already exists",
- args: args{
- store: makeValidSecretStore().Spec.Provider.AWS,
- client: fakesm.Client{
- GetSecretValueFn: fakesm.NewGetSecretValueFn(secretValueOutput, nil),
- PutSecretValueFn: fakesm.NewPutSecretValueFn(putSecretOutput, nil),
- DescribeSecretFn: fakesm.NewDescribeSecretFn(tagSecretOutput, nil),
- TagResourceFn: fakesm.NewTagResourceFn(&awssm.TagResourceOutput{}, nil),
- UntagResourceFn: fakesm.NewUntagResourceFn(&awssm.UntagResourceOutput{}, nil),
- DeleteResourcePolicyFn: fakesm.NewDeleteResourcePolicyFn(&awssm.DeleteResourcePolicyOutput{}, nil),
- },
- pushSecretData: pushSecretDataWithMetadata,
- },
- want: want{
- err: nil,
- },
- },
- "SetSecretSucceedsWithExistingSecretAndKMSKeyAndDescription": {
- reason: "a secret can be pushed to aws secrets manager when it already exists",
- args: args{
- store: makeValidSecretStore().Spec.Provider.AWS,
- client: fakesm.Client{
- GetSecretValueFn: fakesm.NewGetSecretValueFn(secretValueOutput, &getSecretCorrectErr),
- PutSecretValueFn: fakesm.NewPutSecretValueFn(putSecretOutput, nil),
- DescribeSecretFn: fakesm.NewDescribeSecretFn(tagSecretOutput, nil),
- },
- pushSecretData: fake.PushSecretData{SecretKey: secretKey, RemoteKey: fakeKey, Property: "", Metadata: &apiextensionsv1.JSON{
- Raw: []byte(`{
- "apiVersion": "kubernetes.external-secrets.io/v1alpha1",
- "kind": "PushSecretMetadata",
- "spec": {
- "kmsKeyID": "bb123123-b2b0-4f60-ac3a-44a13f0e6b6c",
- "description": "this is a description"
- }
- }`)}},
- },
- want: want{
- err: &getSecretCorrectErr,
- },
- },
- "SetSecretSucceedsWithExistingSecretAndAdditionalTags": {
- reason: "a secret can be pushed to aws secrets manager when it already exists",
- args: args{
- store: makeValidSecretStore().Spec.Provider.AWS,
- client: fakesm.Client{
- GetSecretValueFn: fakesm.NewGetSecretValueFn(secretValueOutput, nil),
- PutSecretValueFn: fakesm.NewPutSecretValueFn(putSecretOutput, nil),
- DescribeSecretFn: fakesm.NewDescribeSecretFn(tagSecretOutput, nil),
- TagResourceFn: fakesm.NewTagResourceFn(&awssm.TagResourceOutput{}, nil),
- UntagResourceFn: fakesm.NewUntagResourceFn(&awssm.UntagResourceOutput{}, nil),
- DeleteResourcePolicyFn: fakesm.NewDeleteResourcePolicyFn(&awssm.DeleteResourcePolicyOutput{}, nil),
- },
- pushSecretData: fake.PushSecretData{SecretKey: secretKey, RemoteKey: fakeKey, Property: "", Metadata: &apiextensionsv1.JSON{
- Raw: []byte(`{
- "apiVersion": "kubernetes.external-secrets.io/v1alpha1",
- "kind": "PushSecretMetadata",
- "spec": {
- "tags": {"tagname12": "tagvalue1"}
- }
- }`)}},
- },
- want: want{
- err: nil,
- },
- },
- "SetSecretSucceedsWithNewSecret": {
- reason: "a secret can be pushed to aws secrets manager if it doesn't already exist",
- args: args{
- store: makeValidSecretStore().Spec.Provider.AWS,
- client: fakesm.Client{
- DescribeSecretFn: fakesm.NewDescribeSecretFn(blankDescribeSecretOutput, &getSecretCorrectErr),
- CreateSecretFn: fakesm.NewCreateSecretFn(secretOutput, nil),
- PutResourcePolicyFn: fakesm.NewPutResourcePolicyFn(&awssm.PutResourcePolicyOutput{}, nil),
- },
- pushSecretData: pushSecretDataWithoutProperty,
- },
- want: want{
- err: nil,
- },
- },
- "SetSecretWithPropertySucceedsWithNewSecret": {
- 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",
- args: args{
- store: makeValidSecretStore().Spec.Provider.AWS,
- client: fakesm.Client{
- DescribeSecretFn: fakesm.NewDescribeSecretFn(blankDescribeSecretOutput, &getSecretCorrectErr),
- CreateSecretFn: fakesm.NewCreateSecretFn(secretOutput, nil, []byte(`{"other-fake-property":"fake-value"}`)),
- },
- pushSecretData: pushSecretDataWithProperty,
- },
- want: want{
- err: nil,
- },
- },
- "SetSecretWithPropertySucceedsWithExistingSecretAndNewPropertyBinary": {
- 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)",
- args: args{
- newUUID: defaultUpdatedVersion,
- store: makeValidSecretStore().Spec.Provider.AWS,
- client: fakesm.Client{
- GetSecretValueFn: fakesm.NewGetSecretValueFn(secretValueOutputFrom(params{b: []byte((`{"fake-property":"fake-value"}`))}), nil),
- DescribeSecretFn: fakesm.NewDescribeSecretFn(tagSecretOutput, nil),
- PutSecretValueFn: fakesm.NewPutSecretValueFn(putSecretOutput, nil, fakesm.ExpectedPutSecretValueInput{
- SecretBinary: []byte(`{"fake-property":"fake-value","other-fake-property":"fake-value"}`),
- Version: &defaultUpdatedVersion,
- }),
- TagResourceFn: fakesm.NewTagResourceFn(&awssm.TagResourceOutput{}, nil),
- UntagResourceFn: fakesm.NewUntagResourceFn(&awssm.UntagResourceOutput{}, nil),
- DeleteResourcePolicyFn: fakesm.NewDeleteResourcePolicyFn(&awssm.DeleteResourcePolicyOutput{}, nil),
- },
- pushSecretData: pushSecretDataWithProperty,
- },
- want: want{
- err: nil,
- },
- },
- "SetSecretWithPropertySucceedsWithExistingSecretAndRandomUUIDVersion": {
- 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",
- args: args{
- store: makeValidSecretStore().Spec.Provider.AWS,
- newUUID: randomUUIDVersionIncremented,
- client: fakesm.Client{
- GetSecretValueFn: fakesm.NewGetSecretValueFn(secretValueOutputFrom(params{
- b: []byte((`{"fake-property":"fake-value"}`)),
- version: &randomUUIDVersion,
- }), nil),
- DescribeSecretFn: fakesm.NewDescribeSecretFn(tagSecretOutputFrom(randomUUIDVersion), nil),
- PutSecretValueFn: fakesm.NewPutSecretValueFn(putSecretOutput, nil, fakesm.ExpectedPutSecretValueInput{
- SecretBinary: []byte(`{"fake-property":"fake-value","other-fake-property":"fake-value"}`),
- Version: &randomUUIDVersionIncremented,
- }),
- TagResourceFn: fakesm.NewTagResourceFn(&awssm.TagResourceOutput{}, nil),
- UntagResourceFn: fakesm.NewUntagResourceFn(&awssm.UntagResourceOutput{}, nil),
- DeleteResourcePolicyFn: fakesm.NewDeleteResourcePolicyFn(&awssm.DeleteResourcePolicyOutput{}, nil),
- },
- pushSecretData: pushSecretDataWithProperty,
- },
- want: want{
- err: nil,
- },
- },
- "SetSecretWithPropertySucceedsWithExistingSecretAndVersionThatCantBeParsed": {
- reason: "A manually set secret version doesn't have to be a UUID",
- args: args{
- newUUID: unparsableVersion,
- store: makeValidSecretStore().Spec.Provider.AWS,
- client: fakesm.Client{
- GetSecretValueFn: fakesm.NewGetSecretValueFn(secretValueOutputFrom(params{
- b: []byte((`{"fake-property":"fake-value"}`)),
- version: &unparsableVersion,
- }), nil),
- DescribeSecretFn: fakesm.NewDescribeSecretFn(tagSecretOutput, nil),
- PutSecretValueFn: fakesm.NewPutSecretValueFn(putSecretOutput, nil, fakesm.ExpectedPutSecretValueInput{
- SecretBinary: []byte((`fake-value`)),
- Version: &unparsableVersion,
- }),
- TagResourceFn: fakesm.NewTagResourceFn(&awssm.TagResourceOutput{}, nil),
- UntagResourceFn: fakesm.NewUntagResourceFn(&awssm.UntagResourceOutput{}, nil),
- DeleteResourcePolicyFn: fakesm.NewDeleteResourcePolicyFn(&awssm.DeleteResourcePolicyOutput{}, nil),
- },
- pushSecretData: pushSecretDataWithoutProperty,
- },
- want: want{
- err: nil,
- },
- },
- "SetSecretWithPropertySucceedsWithExistingSecretAndAbsentVersion": {
- reason: "When a secret version is not specified, set it to 1",
- args: args{
- newUUID: initialVersion,
- store: makeValidSecretStore().Spec.Provider.AWS,
- client: fakesm.Client{
- GetSecretValueFn: fakesm.NewGetSecretValueFn(&awssm.GetSecretValueOutput{
- ARN: &arn,
- SecretBinary: []byte((`{"fake-property":"fake-value"}`)),
- }, nil),
- DescribeSecretFn: fakesm.NewDescribeSecretFn(tagSecretOutput, nil),
- PutSecretValueFn: fakesm.NewPutSecretValueFn(putSecretOutput, nil, fakesm.ExpectedPutSecretValueInput{
- SecretBinary: []byte(`{"fake-property":"fake-value","other-fake-property":"fake-value"}`),
- Version: &initialVersion,
- }),
- TagResourceFn: fakesm.NewTagResourceFn(&awssm.TagResourceOutput{}, nil),
- UntagResourceFn: fakesm.NewUntagResourceFn(&awssm.UntagResourceOutput{}, nil),
- DeleteResourcePolicyFn: fakesm.NewDeleteResourcePolicyFn(&awssm.DeleteResourcePolicyOutput{}, nil),
- },
- pushSecretData: pushSecretDataWithProperty,
- },
- want: want{
- err: nil,
- },
- },
- "SetSecretWithPropertySucceedsWithExistingSecretAndNewPropertyString": {
- 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)",
- args: args{
- newUUID: defaultUpdatedVersion,
- store: makeValidSecretStore().Spec.Provider.AWS,
- client: fakesm.Client{
- GetSecretValueFn: fakesm.NewGetSecretValueFn(secretValueOutputFrom(params{s: `{"fake-property":"fake-value"}`}), nil),
- DescribeSecretFn: fakesm.NewDescribeSecretFn(tagSecretOutput, nil),
- PutSecretValueFn: fakesm.NewPutSecretValueFn(putSecretOutput, nil, fakesm.ExpectedPutSecretValueInput{
- SecretBinary: []byte(`{"fake-property":"fake-value","other-fake-property":"fake-value"}`),
- Version: &defaultUpdatedVersion,
- }),
- TagResourceFn: fakesm.NewTagResourceFn(&awssm.TagResourceOutput{}, nil),
- UntagResourceFn: fakesm.NewUntagResourceFn(&awssm.UntagResourceOutput{}, nil),
- DeleteResourcePolicyFn: fakesm.NewDeleteResourcePolicyFn(&awssm.DeleteResourcePolicyOutput{}, nil),
- },
- pushSecretData: pushSecretDataWithProperty,
- },
- want: want{
- err: nil,
- },
- },
- "SetSecretWithPropertySucceedsWithExistingSecretAndNewPropertyWithDot": {
- 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)",
- args: args{
- newUUID: defaultUpdatedVersion,
- store: makeValidSecretStore().Spec.Provider.AWS,
- client: fakesm.Client{
- GetSecretValueFn: fakesm.NewGetSecretValueFn(secretValueOutputFrom(params{s: `{"fake-property":{"fake-property":"fake-value"}}`}), nil),
- DescribeSecretFn: fakesm.NewDescribeSecretFn(tagSecretOutput, nil),
- PutSecretValueFn: fakesm.NewPutSecretValueFn(putSecretOutput, nil, fakesm.ExpectedPutSecretValueInput{
- SecretBinary: []byte(`{"fake-property":{"fake-property":"fake-value","other-fake-property":"fake-value"}}`),
- Version: &defaultUpdatedVersion,
- }),
- TagResourceFn: fakesm.NewTagResourceFn(&awssm.TagResourceOutput{}, nil),
- UntagResourceFn: fakesm.NewUntagResourceFn(&awssm.UntagResourceOutput{}, nil),
- DeleteResourcePolicyFn: fakesm.NewDeleteResourcePolicyFn(&awssm.DeleteResourcePolicyOutput{}, nil),
- },
- pushSecretData: fake.PushSecretData{SecretKey: secretKey, RemoteKey: fakeKey, Property: "fake-property.other-fake-property"},
- },
- want: want{
- err: nil,
- },
- },
- "SetSecretWithPropertyFailsExistingNonJsonSecret": {
- reason: "setting a pushSecretData property is only supported for json secrets",
- args: args{
- store: makeValidSecretStore().Spec.Provider.AWS,
- client: fakesm.Client{
- GetSecretValueFn: fakesm.NewGetSecretValueFn(secretValueOutputFrom(params{s: `non-json-secret`}), nil),
- DescribeSecretFn: fakesm.NewDescribeSecretFn(tagSecretOutput, nil),
- },
- pushSecretData: pushSecretDataWithProperty,
- },
- want: want{
- err: errors.New("PushSecret for aws secrets manager with a pushSecretData property requires a json secret"),
- },
- },
- "SetSecretCreateSecretFails": {
- reason: "CreateSecretWithContext returns an error if it fails",
- args: args{
- store: makeValidSecretStore().Spec.Provider.AWS,
- client: fakesm.Client{
- DescribeSecretFn: fakesm.NewDescribeSecretFn(blankDescribeSecretOutput, &getSecretCorrectErr),
- CreateSecretFn: fakesm.NewCreateSecretFn(nil, noPermission),
- },
- pushSecretData: pushSecretDataWithoutProperty,
- },
- want: want{
- err: noPermission,
- },
- },
- "SetSecretGetSecretFails": {
- reason: "GetSecretValueWithContext returns an error if it fails",
- args: args{
- store: makeValidSecretStore().Spec.Provider.AWS,
- client: fakesm.Client{
- DescribeSecretFn: fakesm.NewDescribeSecretFn(blankDescribeSecretOutput, noPermission),
- },
- pushSecretData: pushSecretDataWithoutProperty,
- },
- want: want{
- err: noPermission,
- },
- },
- "SetSecretWillNotPushSameSecret": {
- reason: "secret with the same value will not be pushed",
- args: args{
- store: makeValidSecretStore().Spec.Provider.AWS,
- client: fakesm.Client{
- GetSecretValueFn: fakesm.NewGetSecretValueFn(secretValueOutput2, nil),
- DescribeSecretFn: fakesm.NewDescribeSecretFn(tagSecretOutput, nil),
- TagResourceFn: fakesm.NewTagResourceFn(&awssm.TagResourceOutput{}, nil),
- UntagResourceFn: fakesm.NewUntagResourceFn(&awssm.UntagResourceOutput{}, nil),
- DeleteResourcePolicyFn: fakesm.NewDeleteResourcePolicyFn(&awssm.DeleteResourcePolicyOutput{}, nil),
- },
- pushSecretData: pushSecretDataWithoutProperty,
- },
- want: want{
- err: nil,
- },
- },
- "SetSecretPutSecretValueFails": {
- reason: "PutSecretValueWithContext returns an error if it fails",
- args: args{
- store: makeValidSecretStore().Spec.Provider.AWS,
- client: fakesm.Client{
- GetSecretValueFn: fakesm.NewGetSecretValueFn(secretValueOutput, nil),
- PutSecretValueFn: fakesm.NewPutSecretValueFn(nil, noPermission),
- DescribeSecretFn: fakesm.NewDescribeSecretFn(tagSecretOutput, nil),
- TagResourceFn: fakesm.NewTagResourceFn(&awssm.TagResourceOutput{}, nil),
- UntagResourceFn: fakesm.NewUntagResourceFn(&awssm.UntagResourceOutput{}, nil),
- DeleteResourcePolicyFn: fakesm.NewDeleteResourcePolicyFn(&awssm.DeleteResourcePolicyOutput{}, nil),
- },
- pushSecretData: pushSecretDataWithoutProperty,
- },
- want: want{
- err: noPermission,
- },
- },
- "SetSecretWrongGetSecretErrFails": {
- reason: "DescribeSecret errors out when anything except awssm.ErrCodeResourceNotFoundException",
- args: args{
- store: makeValidSecretStore().Spec.Provider.AWS,
- client: fakesm.Client{
- DescribeSecretFn: fakesm.NewDescribeSecretFn(blankDescribeSecretOutput, &getSecretWrongErr),
- },
- pushSecretData: pushSecretDataWithoutProperty,
- },
- want: want{
- err: &getSecretWrongErr,
- },
- },
- "SetSecretDescribeSecretFails": {
- reason: "secret cannot be described",
- args: args{
- store: makeValidSecretStore().Spec.Provider.AWS,
- client: fakesm.Client{
- GetSecretValueFn: fakesm.NewGetSecretValueFn(secretValueOutput, nil),
- DescribeSecretFn: fakesm.NewDescribeSecretFn(nil, noPermission),
- },
- pushSecretData: pushSecretDataWithoutProperty,
- },
- want: want{
- err: noPermission,
- },
- },
- "SetSecretDoesNotOverwriteUntaggedSecret": {
- reason: "secret cannot be described",
- args: args{
- store: makeValidSecretStore().Spec.Provider.AWS,
- client: fakesm.Client{
- GetSecretValueFn: fakesm.NewGetSecretValueFn(secretValueOutput, nil),
- DescribeSecretFn: fakesm.NewDescribeSecretFn(tagSecretOutputFaulty, nil),
- },
- pushSecretData: pushSecretDataWithoutProperty,
- },
- want: want{
- err: errors.New("secret not managed by external-secrets"),
- },
- },
- "PatchSecretTags": {
- reason: "secret key is configured with tags to remove and add",
- args: args{
- store: &esv1.AWSProvider{
- Service: esv1.AWSServiceSecretsManager,
- Region: "eu-west-2",
- },
- client: fakesm.Client{
- GetSecretValueFn: fakesm.NewGetSecretValueFn(secretValueOutputFrom(params{s: `{"fake-property":{"fake-property":"fake-value"}}`}), nil),
- DescribeSecretFn: fakesm.NewDescribeSecretFn(&awssm.DescribeSecretOutput{
- ARN: &arn,
- Tags: []types.Tag{
- {Key: &managedBy, Value: &externalSecrets},
- {Key: new("team"), Value: new("paradox")},
- },
- }, nil),
- PutSecretValueFn: fakesm.NewPutSecretValueFn(putSecretOutput, nil),
- TagResourceFn: fakesm.NewTagResourceFn(&awssm.TagResourceOutput{}, nil, func(input *awssm.TagResourceInput) {
- assert.Len(t, input.Tags, 2)
- assert.Contains(t, input.Tags, types.Tag{Key: &managedBy, Value: &externalSecrets})
- assert.Contains(t, input.Tags, types.Tag{Key: new("env"), Value: new("sandbox")})
- }),
- UntagResourceFn: fakesm.NewUntagResourceFn(&awssm.UntagResourceOutput{}, nil, func(input *awssm.UntagResourceInput) {
- assert.Len(t, input.TagKeys, 1)
- assert.Equal(t, []string{"team"}, input.TagKeys)
- assert.NotContains(t, input.TagKeys, managedBy)
- }),
- DeleteResourcePolicyFn: fakesm.NewDeleteResourcePolicyFn(&awssm.DeleteResourcePolicyOutput{}, nil),
- },
- pushSecretData: fake.PushSecretData{SecretKey: secretKey, RemoteKey: fakeKey, Property: "", Metadata: &apiextensionsv1.JSON{
- Raw: []byte(`{
- "apiVersion": "kubernetes.external-secrets.io/v1alpha1",
- "kind": "PushSecretMetadata",
- "spec": {
- "secretPushFormat": "string",
- "tags": {
- "env": "sandbox"
- }
- }
- }`)}},
- },
- want: want{
- err: nil,
- },
- },
- "SetSecretWithExistingNonChangingResourcePolicy": {
- reason: "sync an existing secret without syncing resource policy that has no change",
- args: args{
- store: makeValidSecretStore().Spec.Provider.AWS,
- client: fakesm.Client{
- // NO call to PutResourcePolicy
- GetSecretValueFn: fakesm.NewGetSecretValueFn(secretValueOutput, nil),
- PutSecretValueFn: fakesm.NewPutSecretValueFn(putSecretOutput, nil),
- DescribeSecretFn: fakesm.NewDescribeSecretFn(tagSecretOutput, nil),
- TagResourceFn: fakesm.NewTagResourceFn(&awssm.TagResourceOutput{}, nil),
- UntagResourceFn: fakesm.NewUntagResourceFn(&awssm.UntagResourceOutput{}, nil),
- GetResourcePolicyFn: fakesm.NewGetResourcePolicyFn(makeValidGetResourcePolicyOutput(), nil),
- },
- pushSecretData: fake.PushSecretData{
- SecretKey: secretKey,
- RemoteKey: fakeKey,
- Property: "",
- Metadata: &apiextensionsv1.JSON{
- Raw: []byte(`{
- "apiVersion": "kubernetes.external-secrets.io/v1alpha1",
- "kind": "PushSecretMetadata",
- "spec": {
- "secretPushFormat": "string",
- "resourcePolicy": {
- "blockPublicPolicy": true,
- "policySourceRef": {
- "kind": "ConfigMap",
- "name": "resource-policy",
- "key": "policy.json"
- }
- }
- }
- }`),
- },
- },
- kubeclient: clientfake.NewFakeClient(&corev1.ConfigMap{
- ObjectMeta: metav1.ObjectMeta{
- Name: "resource-policy",
- },
- // Create a policy that does not match object order of the
- // existing one
- Data: map[string]string{
- "policy.json": `
- {
- "Version": "2012-10-17",
- "Statement": [
- {
- "Resource": "*",
- "Effect": "Deny",
- "Principal": "*",
- "Action": [
- "secretsmanager:PutResourcePolicy",
- "secretsmanager:DeleteResourcePolicy",
- "secretsmanager:GetResourcePolicy"
- ],
- "Condition": {
- "ArnNotEquals": {
- "aws:PrincipalArn": [
- "arn:aws:iam::000000000000:root",
- "arn:aws:iam::000000000000:role/admin"
- ]
- }
- },
- "Sid": "DenyPolicyChangesExceptAdmins"
- }
- ]
- }
- `,
- },
- }),
- },
- want: want{
- err: nil,
- },
- },
- "SetSecretWithExistingChangingResourcePolicy": {
- reason: "sync an existing secret and the resource policy when it has changes",
- args: args{
- store: makeValidSecretStore().Spec.Provider.AWS,
- client: fakesm.Client{
- GetSecretValueFn: fakesm.NewGetSecretValueFn(secretValueOutput, nil),
- PutSecretValueFn: fakesm.NewPutSecretValueFn(putSecretOutput, nil),
- DescribeSecretFn: fakesm.NewDescribeSecretFn(tagSecretOutput, nil),
- TagResourceFn: fakesm.NewTagResourceFn(&awssm.TagResourceOutput{}, nil),
- UntagResourceFn: fakesm.NewUntagResourceFn(&awssm.UntagResourceOutput{}, nil),
- GetResourcePolicyFn: fakesm.NewGetResourcePolicyFn(makeValidGetResourcePolicyOutput(), nil),
- // Call to PutResourcePolicy since policy does not match
- PutResourcePolicyFn: fakesm.NewPutResourcePolicyFn(&awssm.PutResourcePolicyOutput{}, nil),
- },
- pushSecretData: fake.PushSecretData{
- SecretKey: secretKey,
- RemoteKey: fakeKey,
- Property: "",
- Metadata: &apiextensionsv1.JSON{
- Raw: []byte(`{
- "apiVersion": "kubernetes.external-secrets.io/v1alpha1",
- "kind": "PushSecretMetadata",
- "spec": {
- "secretPushFormat": "string",
- "resourcePolicy": {
- "blockPublicPolicy": true,
- "policySourceRef": {
- "kind": "ConfigMap",
- "name": "resource-policy",
- "key": "policy.json"
- }
- }
- }
- }`),
- },
- },
- kubeclient: clientfake.NewFakeClient(&corev1.ConfigMap{
- ObjectMeta: metav1.ObjectMeta{
- Name: "resource-policy",
- },
- // Create a policy that does not match object order of the
- // existing one
- Data: map[string]string{
- "policy.json": `
- {
- "Version": "2012-10-17",
- "Statement": [
- {
- "Resource": "*",
- "Effect": "Deny",
- "Principal": "*",
- "Action": [
- "secretsmanager:PutResourcePolicy",
- "secretsmanager:DeleteResourcePolicy",
- "secretsmanager:GetResourcePolicy"
- ],
- "Condition": {
- "ArnNotEquals": {
- "aws:PrincipalArn": [
- "arn:aws:iam::000000000000:root",
- "arn:aws:iam::000000000000:role/sudo"
- ]
- }
- },
- "Sid": "DenyPolicyChangesExceptAdmins"
- }
- ]
- }
- `,
- },
- }),
- },
- want: want{
- err: nil,
- },
- },
- }
- for name, tc := range tests {
- t.Run(name, func(t *testing.T) {
- sm := SecretsManager{
- client: &tc.args.client,
- prefix: tc.args.store.Prefix,
- newUUID: func() string { return tc.args.newUUID },
- kube: tc.args.kubeclient,
- }
- err := sm.PushSecret(context.Background(), fakeSecret, tc.args.pushSecretData)
- // Error nil XOR tc.want.err nil
- if ((err == nil) || (tc.want.err == nil)) && !((err == nil) && (tc.want.err == nil)) {
- t.Errorf("\nTesting SetSecret:\nName: %v\nReason: %v\nWant error: %v\nGot error: %v", name, tc.reason, tc.want.err, err)
- }
- // if errors are the same type but their contents do not match
- if err != nil && tc.want.err != nil {
- if !strings.Contains(err.Error(), tc.want.err.Error()) {
- t.Errorf("\nTesting SetSecret:\nName: %v\nReason: %v\nWant error: %v\nGot error got nil", name, tc.reason, tc.want.err)
- }
- }
- })
- }
- }
- func TestPushSecretTagsUpdatedWhenValueUnchanged(t *testing.T) {
- secretKey := fakeSecretKey
- secretValue := []byte("fake-value")
- fakeSecret := &corev1.Secret{
- Data: map[string][]byte{
- secretKey: secretValue,
- },
- }
- arn := testARN
- defaultVersion := testDefaultVersion
- managedBy := managedBy
- externalSecrets := externalSecrets
- tagResourceCalled := false
- var capturedTagInput *awssm.TagResourceInput
- client := fakesm.Client{
- GetSecretValueFn: fakesm.NewGetSecretValueFn(&awssm.GetSecretValueOutput{
- ARN: &arn,
- SecretBinary: secretValue,
- VersionId: &defaultVersion,
- }, nil),
- DescribeSecretFn: fakesm.NewDescribeSecretFn(&awssm.DescribeSecretOutput{
- ARN: &arn,
- Tags: []types.Tag{
- {Key: &managedBy, Value: &externalSecrets},
- },
- VersionIdsToStages: map[string][]string{
- defaultVersion: {"AWSCURRENT"},
- },
- }, nil),
- PutSecretValueFn: fakesm.NewPutSecretValueFn(nil, fmt.Errorf("PutSecretValue should not be called when value is unchanged")),
- TagResourceFn: fakesm.NewTagResourceFn(&awssm.TagResourceOutput{}, nil, func(input *awssm.TagResourceInput) {
- tagResourceCalled = true
- capturedTagInput = input
- }),
- UntagResourceFn: fakesm.NewUntagResourceFn(&awssm.UntagResourceOutput{}, nil),
- DeleteResourcePolicyFn: fakesm.NewDeleteResourcePolicyFn(&awssm.DeleteResourcePolicyOutput{}, nil),
- }
- sm := SecretsManager{
- client: &client,
- }
- pushSecretData := fake.PushSecretData{
- SecretKey: secretKey,
- RemoteKey: fakeKey,
- Property: "",
- Metadata: &apiextensionsv1.JSON{
- Raw: []byte(`{
- "apiVersion": "kubernetes.external-secrets.io/v1alpha1",
- "kind": "PushSecretMetadata",
- "spec": {
- "tags": {"newTag": "newValue"}
- }
- }`),
- },
- }
- err := sm.PushSecret(context.Background(), fakeSecret, pushSecretData)
- require.NoError(t, err, "PushSecret should not return error when value is unchanged but tags need updating")
- assert.True(t, tagResourceCalled, "TagResource should be called even when secret value is unchanged")
- require.NotNil(t, capturedTagInput, "TagResourceInput should be captured")
- assert.Len(t, capturedTagInput.Tags, 2)
- assert.Contains(t, capturedTagInput.Tags, types.Tag{Key: &managedBy, Value: &externalSecrets})
- assert.Contains(t, capturedTagInput.Tags, types.Tag{Key: new("newTag"), Value: new("newValue")})
- }
- func TestPushSecretResourcePolicyUpdatedWhenValueUnchanged(t *testing.T) {
- secretKey := fakeSecretKey
- secretValue := []byte("fake-value")
- fakeSecret := &corev1.Secret{
- Data: map[string][]byte{
- secretKey: secretValue,
- },
- }
- arn := testARN
- defaultVersion := testDefaultVersion
- managedBy := managedBy
- externalSecrets := externalSecrets
- putResourcePolicyCalled := false
- var capturedPolicyInput *awssm.PutResourcePolicyInput
- putSecretValueCalled := false
- existingPolicy := `{"Version":"2012-10-17","Statement":[{"Sid":"OldPolicy","Effect":"Deny","Principal":"*","Action":"secretsmanager:GetSecretValue","Resource":"*"}]}`
- newPolicy := `{"Version":"2012-10-17","Statement":[{"Sid":"NewPolicy","Effect":"Allow","Principal":"*","Action":"secretsmanager:GetSecretValue","Resource":"*"}]}`
- client := fakesm.Client{
- GetSecretValueFn: fakesm.NewGetSecretValueFn(&awssm.GetSecretValueOutput{
- ARN: &arn,
- SecretBinary: secretValue,
- VersionId: &defaultVersion,
- }, nil),
- DescribeSecretFn: fakesm.NewDescribeSecretFn(&awssm.DescribeSecretOutput{
- ARN: &arn,
- Tags: []types.Tag{
- {Key: &managedBy, Value: &externalSecrets},
- },
- VersionIdsToStages: map[string][]string{
- defaultVersion: {"AWSCURRENT"},
- },
- }, nil),
- PutSecretValueFn: func(_ context.Context, _ *awssm.PutSecretValueInput, _ ...func(*awssm.Options)) (*awssm.PutSecretValueOutput, error) {
- putSecretValueCalled = true
- return nil, fmt.Errorf("PutSecretValue should not be called when value is unchanged")
- },
- TagResourceFn: fakesm.NewTagResourceFn(&awssm.TagResourceOutput{}, nil),
- UntagResourceFn: fakesm.NewUntagResourceFn(&awssm.UntagResourceOutput{}, nil),
- DeleteResourcePolicyFn: fakesm.NewDeleteResourcePolicyFn(&awssm.DeleteResourcePolicyOutput{}, nil),
- GetResourcePolicyFn: fakesm.NewGetResourcePolicyFn(&awssm.GetResourcePolicyOutput{
- ResourcePolicy: &existingPolicy,
- }, nil),
- PutResourcePolicyFn: fakesm.NewPutResourcePolicyFn(&awssm.PutResourcePolicyOutput{}, nil, func(input *awssm.PutResourcePolicyInput) {
- putResourcePolicyCalled = true
- capturedPolicyInput = input
- }),
- }
- kubeclient := clientfake.NewFakeClient(&corev1.ConfigMap{
- ObjectMeta: metav1.ObjectMeta{
- Name: "resource-policy",
- },
- Data: map[string]string{
- "policy.json": newPolicy,
- },
- })
- sm := SecretsManager{
- client: &client,
- kube: kubeclient,
- }
- pushSecretData := fake.PushSecretData{
- SecretKey: secretKey,
- RemoteKey: fakeKey,
- Property: "",
- Metadata: &apiextensionsv1.JSON{
- Raw: []byte(`{
- "apiVersion": "kubernetes.external-secrets.io/v1alpha1",
- "kind": "PushSecretMetadata",
- "spec": {
- "resourcePolicy": {
- "blockPublicPolicy": true,
- "policySourceRef": {
- "kind": "ConfigMap",
- "name": "resource-policy",
- "key": "policy.json"
- }
- }
- }
- }`),
- },
- }
- err := sm.PushSecret(context.Background(), fakeSecret, pushSecretData)
- require.NoError(t, err, "PushSecret should not return error when value is unchanged but resource policy needs updating")
- assert.True(t, putResourcePolicyCalled, "PutResourcePolicy should be called even when secret value is unchanged")
- assert.False(t, putSecretValueCalled, "PutSecretValue should not be called when value is unchanged")
- require.NotNil(t, capturedPolicyInput, "PutResourcePolicyInput should be captured")
- assert.Equal(t, fakeKey, *capturedPolicyInput.SecretId)
- assert.JSONEq(t, newPolicy, *capturedPolicyInput.ResourcePolicy)
- }
- func TestDeleteSecret(t *testing.T) {
- fakeClient := fakesm.Client{}
- managed := managedBy
- manager := externalSecrets
- secretTag := types.Tag{
- Key: &managed,
- Value: &manager,
- }
- type args struct {
- client fakesm.Client
- config esv1.SecretsManager
- prefix string
- getSecretOutput *awssm.GetSecretValueOutput
- describeSecretOutput *awssm.DescribeSecretOutput
- deleteSecretOutput *awssm.DeleteSecretOutput
- getSecretErr error
- describeSecretErr error
- deleteSecretErr error
- }
- type want struct {
- err error
- }
- type testCase struct {
- args args
- want want
- reason string
- }
- tests := map[string]testCase{
- "Deletes Successfully": {
- args: args{
- client: fakeClient,
- config: esv1.SecretsManager{},
- getSecretOutput: &awssm.GetSecretValueOutput{},
- describeSecretOutput: &awssm.DescribeSecretOutput{
- Tags: []types.Tag{secretTag},
- },
- deleteSecretOutput: &awssm.DeleteSecretOutput{},
- getSecretErr: nil,
- describeSecretErr: nil,
- deleteSecretErr: nil,
- },
- want: want{
- err: nil,
- },
- reason: "",
- },
- "Deletes Successfully with ForceDeleteWithoutRecovery": {
- args: args{
- client: fakeClient,
- config: esv1.SecretsManager{
- ForceDeleteWithoutRecovery: true,
- },
- getSecretOutput: &awssm.GetSecretValueOutput{},
- describeSecretOutput: &awssm.DescribeSecretOutput{
- Tags: []types.Tag{secretTag},
- },
- deleteSecretOutput: &awssm.DeleteSecretOutput{
- DeletionDate: aws.Time(time.Now()),
- },
- getSecretErr: nil,
- describeSecretErr: nil,
- deleteSecretErr: nil,
- },
- want: want{
- err: nil,
- },
- reason: "",
- },
- "Not Managed by ESO": {
- args: args{
- client: fakeClient,
- config: esv1.SecretsManager{},
- getSecretOutput: &awssm.GetSecretValueOutput{},
- describeSecretOutput: &awssm.DescribeSecretOutput{
- Tags: []types.Tag{},
- },
- deleteSecretOutput: &awssm.DeleteSecretOutput{},
- getSecretErr: nil,
- describeSecretErr: nil,
- deleteSecretErr: nil,
- },
- want: want{
- err: nil,
- },
- reason: "",
- },
- "Invalid Recovery Window": {
- args: args{
- client: fakesm.Client{},
- config: esv1.SecretsManager{
- RecoveryWindowInDays: 1,
- },
- getSecretOutput: &awssm.GetSecretValueOutput{},
- describeSecretOutput: &awssm.DescribeSecretOutput{
- Tags: []types.Tag{secretTag},
- },
- deleteSecretOutput: &awssm.DeleteSecretOutput{},
- getSecretErr: nil,
- describeSecretErr: nil,
- deleteSecretErr: nil,
- },
- want: want{
- err: errors.New("invalid DeleteSecretInput: RecoveryWindowInDays must be between 7 and 30 days"),
- },
- reason: "",
- },
- "RecoveryWindowInDays is supplied with ForceDeleteWithoutRecovery": {
- args: args{
- client: fakesm.Client{},
- config: esv1.SecretsManager{
- RecoveryWindowInDays: 7,
- ForceDeleteWithoutRecovery: true,
- },
- getSecretOutput: &awssm.GetSecretValueOutput{},
- describeSecretOutput: &awssm.DescribeSecretOutput{
- Tags: []types.Tag{secretTag},
- },
- deleteSecretOutput: &awssm.DeleteSecretOutput{},
- getSecretErr: nil,
- describeSecretErr: nil,
- deleteSecretErr: nil,
- },
- want: want{
- err: errors.New("invalid DeleteSecretInput: ForceDeleteWithoutRecovery conflicts with RecoveryWindowInDays"),
- },
- reason: "",
- },
- "Failed to get Tags": {
- args: args{
- client: fakeClient,
- config: esv1.SecretsManager{},
- getSecretOutput: &awssm.GetSecretValueOutput{},
- describeSecretOutput: nil,
- deleteSecretOutput: nil,
- getSecretErr: nil,
- describeSecretErr: errors.New("failed to get tags"),
- deleteSecretErr: nil,
- },
- want: want{
- err: errors.New("failed to get tags"),
- },
- reason: "",
- },
- "Secret Not Found": {
- args: args{
- client: fakeClient,
- config: esv1.SecretsManager{},
- getSecretOutput: nil,
- describeSecretOutput: nil,
- deleteSecretOutput: nil,
- getSecretErr: errors.New("not here, sorry dude"),
- describeSecretErr: nil,
- deleteSecretErr: nil,
- },
- want: want{
- err: errors.New("not here, sorry dude"),
- },
- },
- "Not expected AWS error": {
- args: args{
- client: fakeClient,
- config: esv1.SecretsManager{},
- getSecretOutput: nil,
- describeSecretOutput: nil,
- deleteSecretOutput: nil,
- getSecretErr: errors.New("aws unavailable"),
- describeSecretErr: nil,
- deleteSecretErr: nil,
- },
- want: want{
- err: errors.New("aws unavailable"),
- },
- },
- "unexpected error": {
- args: args{
- client: fakeClient,
- config: esv1.SecretsManager{},
- getSecretOutput: nil,
- describeSecretOutput: nil,
- deleteSecretOutput: nil,
- getSecretErr: errors.New("timeout"),
- describeSecretErr: nil,
- deleteSecretErr: nil,
- },
- want: want{
- err: errors.New("timeout"),
- },
- },
- "DeleteWithPrefix": {
- args: args{
- client: fakesm.Client{
- GetSecretValueFn: func(ctx context.Context, input *awssm.GetSecretValueInput, opts ...func(*awssm.Options)) (*awssm.GetSecretValueOutput, error) {
- // Verify that the input secret ID has the prefix applied
- if *input.SecretId != "my-prefix-"+fakeKey {
- return nil, fmt.Errorf("expected secret name to be prefixed with 'my-prefix-', got %s", *input.SecretId)
- }
- return &awssm.GetSecretValueOutput{}, nil
- },
- DescribeSecretFn: func(ctx context.Context, input *awssm.DescribeSecretInput, opts ...func(*awssm.Options)) (*awssm.DescribeSecretOutput, error) {
- // Verify that the input secret ID has the prefix applied
- if *input.SecretId != "my-prefix-"+fakeKey {
- return nil, fmt.Errorf("expected secret name to be prefixed with 'my-prefix-', got %s", *input.SecretId)
- }
- return &awssm.DescribeSecretOutput{
- Tags: []types.Tag{secretTag},
- }, nil
- },
- DeleteSecretFn: func(ctx context.Context, input *awssm.DeleteSecretInput, opts ...func(*awssm.Options)) (*awssm.DeleteSecretOutput, error) {
- return &awssm.DeleteSecretOutput{}, nil
- },
- },
- config: esv1.SecretsManager{},
- prefix: "my-prefix-",
- getSecretOutput: nil,
- describeSecretOutput: nil,
- deleteSecretOutput: nil,
- getSecretErr: nil,
- describeSecretErr: nil,
- deleteSecretErr: nil,
- },
- want: want{
- err: nil,
- },
- reason: "Verifies that the prefix is correctly applied when deleting a secret",
- },
- }
- for name, tc := range tests {
- t.Run(name, func(t *testing.T) {
- ref := fake.PushSecretData{RemoteKey: fakeKey}
- sm := SecretsManager{
- client: &tc.args.client,
- config: &tc.args.config,
- prefix: tc.args.prefix,
- }
- if tc.args.client.GetSecretValueFn == nil {
- tc.args.client.GetSecretValueFn = fakesm.NewGetSecretValueFn(tc.args.getSecretOutput, tc.args.getSecretErr)
- }
- if tc.args.client.DescribeSecretFn == nil {
- tc.args.client.DescribeSecretFn = fakesm.NewDescribeSecretFn(tc.args.describeSecretOutput, tc.args.describeSecretErr)
- }
- if tc.args.client.DeleteSecretFn == nil {
- tc.args.client.DeleteSecretFn = fakesm.NewDeleteSecretFn(tc.args.deleteSecretOutput, tc.args.deleteSecretErr)
- }
- err := sm.DeleteSecret(context.TODO(), ref)
- t.Logf("DeleteSecret error: %v", err)
- // Error nil XOR tc.want.err nil
- if ((err == nil) || (tc.want.err == nil)) && !((err == nil) && (tc.want.err == nil)) {
- t.Errorf("\nTesting DeleteSecret:\nName: %v\nReason: %v\nWant error: %v\nGot error: %v", name, tc.reason, tc.want.err, err)
- }
- // if errors are the same type but their contents do not match
- if err != nil && tc.want.err != nil {
- if !strings.Contains(err.Error(), tc.want.err.Error()) {
- t.Errorf("\nTesting DeleteSecret:\nName: %v\nReason: %v\nWant error: %v\nGot error got nil", name, tc.reason, tc.want.err)
- }
- }
- })
- }
- }
- func makeValidSecretStore() *esv1.SecretStore {
- return &esv1.SecretStore{
- ObjectMeta: metav1.ObjectMeta{
- Name: "aws-secret-store",
- Namespace: "default",
- },
- Spec: esv1.SecretStoreSpec{
- Provider: &esv1.SecretStoreProvider{
- AWS: &esv1.AWSProvider{
- Service: esv1.AWSServiceSecretsManager,
- Region: "eu-west-2",
- },
- },
- },
- }
- }
- func getTagSlice() []types.Tag {
- tagKey1 := tagname1
- tagValue1 := tagvalue1
- tagKey2 := tagname2
- tagValue2 := tagvalue2
- return []types.Tag{
- {
- Key: &tagKey1,
- Value: &tagValue1,
- },
- {
- Key: &tagKey2,
- Value: &tagValue2,
- },
- }
- }
- func TestSecretsManagerGetAllSecrets(t *testing.T) {
- ctx := context.Background()
- errBoom := errors.New("boom")
- secretName := "my-secret"
- secretVersion := "AWSCURRENT"
- secretPath := "/path/to/secret"
- secretValue := "secret value"
- secretTags := map[string]string{
- "foo": "bar",
- }
- // Test cases
- testCases := []struct {
- name string
- ref esv1.ExternalSecretFind
- secretName string
- secretVersion string
- secretValue string
- batchGetSecretValueFn func(context.Context, *awssm.BatchGetSecretValueInput, ...func(*awssm.Options)) (*awssm.BatchGetSecretValueOutput, error)
- listSecretsFn func(context.Context, *awssm.ListSecretsInput, ...func(*awssm.Options)) (*awssm.ListSecretsOutput, error)
- getSecretValueFn func(context.Context, *awssm.GetSecretValueInput, ...func(*awssm.Options)) (*awssm.GetSecretValueOutput, error)
- expectedData map[string][]byte
- expectedError string
- }{
- {
- name: "Matching secrets found",
- ref: esv1.ExternalSecretFind{
- Name: &esv1.FindName{
- RegExp: secretName,
- },
- Path: new(secretPath),
- },
- secretName: secretName,
- secretVersion: secretVersion,
- secretValue: secretValue,
- batchGetSecretValueFn: func(_ context.Context, input *awssm.BatchGetSecretValueInput, _ ...func(*awssm.Options)) (*awssm.BatchGetSecretValueOutput, error) {
- assert.Len(t, input.Filters, 1)
- assert.Equal(t, "name", string(input.Filters[0].Key))
- assert.Equal(t, secretPath, input.Filters[0].Values[0])
- return &awssm.BatchGetSecretValueOutput{
- SecretValues: []types.SecretValueEntry{
- {
- Name: new(secretName),
- VersionStages: []string{secretVersion},
- SecretBinary: []byte(secretValue),
- },
- },
- }, nil
- },
- expectedData: map[string][]byte{
- secretName: []byte(secretValue),
- },
- expectedError: "",
- },
- {
- name: "Error occurred while fetching secret value",
- ref: esv1.ExternalSecretFind{
- Name: &esv1.FindName{
- RegExp: secretName,
- },
- Path: new(secretPath),
- },
- secretName: secretName,
- secretVersion: secretVersion,
- secretValue: secretValue,
- batchGetSecretValueFn: func(_ context.Context, input *awssm.BatchGetSecretValueInput, _ ...func(*awssm.Options)) (*awssm.BatchGetSecretValueOutput, error) {
- return &awssm.BatchGetSecretValueOutput{
- SecretValues: []types.SecretValueEntry{
- {
- Name: new(secretName),
- },
- },
- }, errBoom
- },
- expectedData: nil,
- expectedError: errBoom.Error(),
- },
- {
- name: "regexp: error occurred while listing secrets",
- ref: esv1.ExternalSecretFind{
- Name: &esv1.FindName{
- RegExp: secretName,
- },
- },
- listSecretsFn: func(_ context.Context, input *awssm.ListSecretsInput, _ ...func(*awssm.Options)) (*awssm.ListSecretsOutput, error) {
- return nil, errBoom
- },
- expectedData: nil,
- expectedError: errBoom.Error(),
- },
- {
- name: "regep: no matching secrets found",
- ref: esv1.ExternalSecretFind{
- Name: &esv1.FindName{
- RegExp: secretName,
- },
- },
- listSecretsFn: func(_ context.Context, input *awssm.ListSecretsInput, _ ...func(*awssm.Options)) (*awssm.ListSecretsOutput, error) {
- return &awssm.ListSecretsOutput{
- SecretList: []types.SecretListEntry{
- {
- Name: new("other-secret"),
- },
- },
- }, nil
- },
- batchGetSecretValueFn: func(_ context.Context, input *awssm.BatchGetSecretValueInput, _ ...func(*awssm.Options)) (*awssm.BatchGetSecretValueOutput, error) {
- return &awssm.BatchGetSecretValueOutput{
- SecretValues: []types.SecretValueEntry{
- {
- Name: new("other-secret"),
- },
- },
- }, nil
- },
- expectedData: make(map[string][]byte),
- expectedError: "",
- },
- {
- name: "invalid regexp",
- ref: esv1.ExternalSecretFind{
- Name: &esv1.FindName{
- RegExp: "[",
- },
- },
- expectedData: nil,
- expectedError: "could not compile find.name.regexp [[]: error parsing regexp: missing closing ]: `[`",
- },
- {
- name: "tags: Matching secrets found",
- ref: esv1.ExternalSecretFind{
- Tags: secretTags,
- },
- secretName: secretName,
- secretVersion: secretVersion,
- secretValue: secretValue,
- batchGetSecretValueFn: func(_ context.Context, input *awssm.BatchGetSecretValueInput, _ ...func(*awssm.Options)) (*awssm.BatchGetSecretValueOutput, error) {
- assert.Len(t, input.Filters, 2)
- assert.Equal(t, "tag-key", string(input.Filters[0].Key))
- assert.Equal(t, "foo", input.Filters[0].Values[0])
- assert.Equal(t, "tag-value", string(input.Filters[1].Key))
- assert.Equal(t, "bar", input.Filters[1].Values[0])
- return &awssm.BatchGetSecretValueOutput{
- SecretValues: []types.SecretValueEntry{
- {
- Name: new(secretName),
- VersionStages: []string{secretVersion},
- SecretBinary: []byte(secretValue),
- },
- },
- }, nil
- },
- expectedData: map[string][]byte{
- secretName: []byte(secretValue),
- },
- expectedError: "",
- },
- {
- name: "name and tags: matching secrets found",
- ref: esv1.ExternalSecretFind{
- Name: &esv1.FindName{
- RegExp: secretName,
- },
- Tags: secretTags,
- },
- listSecretsFn: func(_ context.Context, input *awssm.ListSecretsInput, _ ...func(*awssm.Options)) (*awssm.ListSecretsOutput, error) {
- allSecrets := []types.SecretListEntry{
- {
- Name: new(secretName),
- Tags: []types.Tag{
- {Key: new("foo"), Value: new("bar")},
- },
- },
- {
- Name: new(fmt.Sprintf("%ssomeothertext", secretName)),
- },
- {
- Name: new("unmatched-secret"),
- Tags: []types.Tag{
- {Key: new("foo"), Value: new("bar")},
- },
- },
- }
- filtered := make([]types.SecretListEntry, 0, len(allSecrets))
- for _, secret := range allSecrets {
- exclude := false
- tagMap := map[string]string{}
- for _, t := range secret.Tags {
- if t.Key != nil && t.Value != nil {
- tagMap[*t.Key] = *t.Value
- }
- }
- for _, f := range input.Filters {
- switch f.Key {
- case types.FilterNameStringTypeName:
- if secret.Name != nil {
- for _, v := range f.Values {
- if strings.Contains(*secret.Name, v) {
- exclude = true
- break
- }
- }
- }
- case types.FilterNameStringTypeTagKey:
- for _, v := range f.Values {
- if tagMap[v] == "" {
- exclude = true
- break
- }
- }
- case types.FilterNameStringTypeDescription,
- types.FilterNameStringTypeTagValue,
- types.FilterNameStringTypePrimaryRegion,
- types.FilterNameStringTypeOwningService,
- types.FilterNameStringTypeAll:
- continue
- }
- }
- if !exclude {
- filtered = append(filtered, secret)
- }
- }
- return &awssm.ListSecretsOutput{SecretList: filtered}, nil
- },
- getSecretValueFn: func(_ context.Context, input *awssm.GetSecretValueInput, _ ...func(*awssm.Options)) (*awssm.GetSecretValueOutput, error) {
- if *input.SecretId == secretName {
- return &awssm.GetSecretValueOutput{
- Name: new(secretName),
- VersionStages: []string{secretVersion},
- SecretBinary: []byte(secretValue),
- }, nil
- }
- if *input.SecretId == "unmatched-secret" {
- return &awssm.GetSecretValueOutput{
- Name: new("unmatched-secret"),
- VersionStages: []string{secretVersion},
- SecretBinary: []byte("othervalue"),
- }, nil
- }
- return &awssm.GetSecretValueOutput{
- Name: new(fmt.Sprintf("%ssomeothertext", secretName)),
- VersionStages: []string{secretVersion},
- SecretBinary: []byte("someothervalue"),
- }, nil
- },
- expectedData: map[string][]byte{
- secretName: []byte(secretValue),
- },
- expectedError: "",
- },
- {
- name: "tags: error occurred while fetching secret value",
- ref: esv1.ExternalSecretFind{
- Tags: secretTags,
- },
- secretName: secretName,
- secretVersion: secretVersion,
- secretValue: secretValue,
- batchGetSecretValueFn: func(_ context.Context, input *awssm.BatchGetSecretValueInput, _ ...func(*awssm.Options)) (*awssm.BatchGetSecretValueOutput, error) {
- return &awssm.BatchGetSecretValueOutput{
- SecretValues: []types.SecretValueEntry{
- {
- Name: new(secretName),
- VersionStages: []string{secretVersion},
- SecretBinary: []byte(secretValue),
- },
- },
- }, errBoom
- },
- expectedData: nil,
- expectedError: errBoom.Error(),
- },
- {
- name: "tags: error occurred while listing secrets",
- ref: esv1.ExternalSecretFind{
- Tags: secretTags,
- },
- batchGetSecretValueFn: func(_ context.Context, input *awssm.BatchGetSecretValueInput, _ ...func(*awssm.Options)) (*awssm.BatchGetSecretValueOutput, error) {
- return nil, errBoom
- },
- expectedData: nil,
- expectedError: errBoom.Error(),
- },
- }
- for _, tc := range testCases {
- t.Run(tc.name, func(t *testing.T) {
- fc := fakesm.NewClient()
- fc.BatchGetSecretValueFn = tc.batchGetSecretValueFn
- fc.ListSecretsFn = tc.listSecretsFn
- fc.GetSecretValueFn = tc.getSecretValueFn
- sm := SecretsManager{
- client: fc,
- cache: make(map[string]*awssm.GetSecretValueOutput),
- }
- data, err := sm.GetAllSecrets(ctx, tc.ref)
- if err != nil && err.Error() != tc.expectedError {
- t.Errorf("unexpected error: got %v, want %v", err, tc.expectedError)
- }
- if !reflect.DeepEqual(data, tc.expectedData) {
- t.Errorf("unexpected data: got %v, want %v", data, tc.expectedData)
- }
- })
- }
- }
- func TestSecretsManagerValidate(t *testing.T) {
- type fields struct {
- cfg *aws.Config
- referentAuth bool
- }
- validConfig := &aws.Config{
- Credentials: credentials.NewStaticCredentialsProvider(
- "fake",
- "fake",
- "fake",
- ),
- }
- invalidConfig := &aws.Config{
- Credentials: &FakeCredProvider{
- retrieveFunc: func() (aws.Credentials, error) {
- return aws.Credentials{}, errors.New("invalid credentials")
- },
- },
- }
- tests := []struct {
- name string
- fields fields
- want esv1.ValidationResult
- wantErr bool
- }{
- {
- name: "ReferentAuth should always return unknown",
- fields: fields{
- referentAuth: true,
- },
- want: esv1.ValidationResultUnknown,
- },
- {
- name: "Valid credentials should return ready",
- fields: fields{
- cfg: validConfig,
- },
- want: esv1.ValidationResultReady,
- },
- {
- name: "Invalid credentials should return error",
- fields: fields{
- cfg: invalidConfig,
- },
- want: esv1.ValidationResultError,
- wantErr: true,
- },
- }
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- sm := &SecretsManager{
- cfg: tt.fields.cfg,
- referentAuth: tt.fields.referentAuth,
- }
- got, err := sm.Validate()
- if (err != nil) != tt.wantErr {
- t.Errorf("SecretsManager.Validate() error = %v, wantErr %v", err, tt.wantErr)
- return
- }
- if !reflect.DeepEqual(got, tt.want) {
- t.Errorf("SecretsManager.Validate() = %v, want %v", got, tt.want)
- }
- })
- }
- }
- func TestSecretExists(t *testing.T) {
- arn := testARN
- defaultVersion := testDefaultVersion
- secretValueOutput := &awssm.GetSecretValueOutput{
- ARN: &arn,
- VersionId: &defaultVersion,
- }
- blankSecretValueOutput := &awssm.GetSecretValueOutput{}
- getSecretCorrectErr := types.ResourceNotFoundException{}
- getSecretWrongErr := types.InvalidRequestException{}
- pushSecretDataWithoutProperty := fake.PushSecretData{SecretKey: fakeSecretKey, RemoteKey: fakeKey, Property: ""}
- type args struct {
- store *esv1.AWSProvider
- client fakesm.Client
- pushSecretData fake.PushSecretData
- }
- type want struct {
- err error
- wantError bool
- }
- tests := map[string]struct {
- args args
- want want
- }{
- "SecretExistsReturnsTrueForExistingSecret": {
- args: args{
- store: makeValidSecretStore().Spec.Provider.AWS,
- client: fakesm.Client{
- GetSecretValueFn: fakesm.NewGetSecretValueFn(secretValueOutput, nil),
- },
- pushSecretData: pushSecretDataWithoutProperty,
- },
- want: want{
- err: nil,
- wantError: true,
- },
- },
- "SecretExistsReturnsFalseForNonExistingSecret": {
- args: args{
- store: makeValidSecretStore().Spec.Provider.AWS,
- client: fakesm.Client{
- GetSecretValueFn: fakesm.NewGetSecretValueFn(blankSecretValueOutput, &getSecretCorrectErr),
- },
- pushSecretData: pushSecretDataWithoutProperty,
- },
- want: want{
- err: nil,
- wantError: false,
- },
- },
- "SecretExistsReturnsFalseForErroredSecret": {
- args: args{
- store: makeValidSecretStore().Spec.Provider.AWS,
- client: fakesm.Client{
- GetSecretValueFn: fakesm.NewGetSecretValueFn(blankSecretValueOutput, &getSecretWrongErr),
- },
- pushSecretData: pushSecretDataWithoutProperty,
- },
- want: want{
- err: &getSecretWrongErr,
- wantError: false,
- },
- },
- }
- for name, tc := range tests {
- t.Run(name, func(t *testing.T) {
- sm := &SecretsManager{
- client: &tc.args.client,
- }
- got, err := sm.SecretExists(context.Background(), tc.args.pushSecretData)
- assert.Equal(
- t,
- tc.want,
- want{
- err: err,
- wantError: got,
- })
- })
- }
- }
- func TestConstructMetadataWithDefaults(t *testing.T) {
- tests := []struct {
- name string
- input *apiextensionsv1.JSON
- expected *metadata.PushSecretMetadata[PushSecretMetadataSpec]
- expectError bool
- }{
- {
- name: "Valid metadata with multiple fields",
- input: &apiextensionsv1.JSON{Raw: []byte(`{
- "apiVersion": "kubernetes.external-secrets.io/v1alpha1",
- "kind": "PushSecretMetadata",
- "spec": {
- "description": "test description",
- "secretPushFormat":"string",
- "kmsKeyID": "custom-kms-key",
- "tags": {
- "customKey": "customValue"
- },
- }
- }`)},
- expected: &metadata.PushSecretMetadata[PushSecretMetadataSpec]{
- APIVersion: "kubernetes.external-secrets.io/v1alpha1",
- Kind: "PushSecretMetadata",
- Spec: PushSecretMetadataSpec{
- Description: "test description",
- SecretPushFormat: "string",
- KMSKeyID: "custom-kms-key",
- Tags: map[string]string{
- "customKey": "customValue",
- managedBy: externalSecrets,
- },
- },
- },
- },
- {
- name: "Empty metadata, defaults applied",
- input: nil,
- expected: &metadata.PushSecretMetadata[PushSecretMetadataSpec]{
- Spec: PushSecretMetadataSpec{
- Description: fmt.Sprintf("secret '%s:%s'", managedBy, externalSecrets),
- SecretPushFormat: "binary",
- KMSKeyID: "alias/aws/secretsmanager",
- Tags: map[string]string{
- managedBy: externalSecrets,
- },
- },
- },
- },
- {
- name: "Added default metadata with 'managed-by' tag",
- input: &apiextensionsv1.JSON{Raw: []byte(`{
- "apiVersion": "kubernetes.external-secrets.io/v1alpha1",
- "kind": "PushSecretMetadata",
- "spec": {
- "tags": {
- "managed-by": "external-secrets",
- "customKey": "customValue"
- },
- }
- }`)},
- expected: nil,
- expectError: true,
- },
- {
- name: "Invalid metadata format",
- input: &apiextensionsv1.JSON{Raw: []byte(`invalid-json`)},
- expected: nil,
- expectError: true,
- },
- {
- name: "Metadata with 'managed-by' tag specified",
- input: &apiextensionsv1.JSON{Raw: []byte(`{"tags":{"managed-by":"invalid"}}`)},
- expected: nil,
- expectError: true,
- },
- }
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- result, err := (&SecretsManager{}).constructMetadataWithDefaults(tt.input)
- if tt.expectError {
- assert.Error(t, err)
- } else {
- assert.NoError(t, err)
- assert.Equal(t, tt.expected, result)
- }
- })
- }
- }
- func TestComputeTagsToUpdate(t *testing.T) {
- tests := []struct {
- name string
- tags map[string]string
- metaTags map[string]string
- expected []types.Tag
- modified bool
- }{
- {
- name: "No tags to update",
- tags: map[string]string{
- "key1": "value1",
- "key2": "value2",
- },
- metaTags: map[string]string{
- "key1": "value1",
- "key2": "value2",
- },
- expected: []types.Tag{
- {Key: new("key1"), Value: new("value1")},
- {Key: new("key2"), Value: new("value2")},
- },
- modified: false,
- },
- {
- name: "No tags to update as managed-by tag is ignored",
- tags: map[string]string{
- "key1": "value1",
- "key2": "value2",
- },
- metaTags: map[string]string{
- "key1": "value1",
- "key2": "value2",
- managedBy: externalSecrets,
- },
- expected: []types.Tag{
- {Key: new("key1"), Value: new("value1")},
- {Key: new("key2"), Value: new("value2")},
- {Key: new(managedBy), Value: new(externalSecrets)},
- },
- modified: false,
- },
- {
- name: "Add new tag",
- tags: map[string]string{
- "key1": "value1",
- },
- metaTags: map[string]string{
- "key1": "value1",
- "key2": "value2",
- },
- expected: []types.Tag{
- {Key: new("key1"), Value: new("value1")},
- {Key: new("key2"), Value: new("value2")},
- },
- modified: true,
- },
- {
- name: "Update existing tag value",
- tags: map[string]string{
- "key1": "value1",
- },
- metaTags: map[string]string{
- "key1": "newValue",
- },
- expected: []types.Tag{
- {Key: new("key1"), Value: new("newValue")},
- },
- modified: true,
- },
- {
- name: "Empty tags and metaTags",
- tags: map[string]string{},
- metaTags: map[string]string{},
- expected: []types.Tag{},
- modified: false,
- },
- {
- name: "Empty tags with non-empty metaTags",
- tags: map[string]string{},
- metaTags: map[string]string{
- "key1": "value1",
- },
- expected: []types.Tag{
- {Key: new("key1"), Value: new("value1")},
- },
- modified: true,
- },
- }
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- result, modified := computeTagsToUpdate(tt.tags, tt.metaTags)
- assert.ElementsMatch(t, tt.expected, result)
- assert.Equal(t, tt.modified, modified)
- })
- }
- }
- func TestPatchTags(t *testing.T) {
- type call struct {
- untagCalled bool
- tagCalled bool
- }
- tests := []struct {
- name string
- existingTags map[string]string
- metaTags map[string]string
- expectUntag bool
- expectTag bool
- assertsTag func(input *awssm.TagResourceInput)
- assertsUntag func(input *awssm.UntagResourceInput)
- }{
- {
- name: "no changes",
- existingTags: map[string]string{"a": "1"},
- metaTags: map[string]string{"a": "1"},
- expectUntag: false,
- expectTag: false,
- assertsTag: func(input *awssm.TagResourceInput) {
- assert.Fail(t, "Expected TagResource to not be called")
- },
- assertsUntag: func(input *awssm.UntagResourceInput) {
- assert.Fail(t, "Expected UntagResource to not be called")
- },
- },
- {
- name: "update tag value",
- existingTags: map[string]string{"a": "1"},
- metaTags: map[string]string{"a": "2"},
- expectUntag: false,
- expectTag: true,
- assertsTag: func(input *awssm.TagResourceInput) {
- assert.Contains(t, input.Tags, types.Tag{Key: new(managedBy), Value: new(externalSecrets)})
- assert.Contains(t, input.Tags, types.Tag{Key: new("a"), Value: new("2")})
- },
- assertsUntag: func(input *awssm.UntagResourceInput) {
- assert.Fail(t, "Expected UntagResource to not be called")
- },
- },
- {
- name: "remove tag",
- existingTags: map[string]string{"a": "1", "b": "2"},
- metaTags: map[string]string{"a": "1"},
- expectUntag: true,
- expectTag: false,
- assertsTag: func(input *awssm.TagResourceInput) {
- assert.Fail(t, "Expected TagResource to not be called")
- },
- assertsUntag: func(input *awssm.UntagResourceInput) {
- assert.Equal(t, []string{"b"}, input.TagKeys)
- },
- },
- {
- name: "add tags",
- existingTags: map[string]string{"a": "1"},
- metaTags: map[string]string{"a": "1", "b": "2"},
- expectUntag: false,
- expectTag: true,
- assertsTag: func(input *awssm.TagResourceInput) {
- assert.Contains(t, input.Tags, types.Tag{Key: new(managedBy), Value: new(externalSecrets)})
- assert.Contains(t, input.Tags, types.Tag{Key: new("a"), Value: new("1")})
- assert.Contains(t, input.Tags, types.Tag{Key: new("b"), Value: new("2")})
- },
- assertsUntag: func(input *awssm.UntagResourceInput) {
- assert.Fail(t, "Expected UntagResource to not be called")
- },
- },
- }
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- calls := call{}
- fakeClient := &fakesm.Client{
- TagResourceFn: fakesm.NewTagResourceFn(&awssm.TagResourceOutput{}, nil, func(input *awssm.TagResourceInput) {
- tt.assertsTag(input)
- calls.tagCalled = true
- }),
- UntagResourceFn: fakesm.NewUntagResourceFn(&awssm.UntagResourceOutput{}, nil, func(input *awssm.UntagResourceInput) {
- tt.assertsUntag(input)
- calls.untagCalled = true
- }),
- }
- sm := &SecretsManager{client: fakeClient}
- metaMap := map[string]any{
- "apiVersion": "kubernetes.external-secrets.io/v1alpha1",
- "kind": "PushSecretMetadata",
- "spec": map[string]any{
- "description": "adding managed-by tag explicitly",
- "tags": tt.metaTags,
- },
- }
- raw, err := json.Marshal(metaMap)
- require.NoError(t, err)
- meta := &apiextensionsv1.JSON{Raw: raw}
- secretId := "secret"
- err = sm.patchTags(context.Background(), meta, &secretId, tt.existingTags)
- require.NoError(t, err)
- assert.Equal(t, tt.expectUntag, calls.untagCalled)
- assert.Equal(t, tt.expectTag, calls.tagCalled)
- })
- }
- }
- // FakeCredProvider implements the AWS credentials.Provider interface
- // It is used to inject an error into the AWS config to cause a
- // validation error.
- type FakeCredProvider struct {
- retrieveFunc func() (aws.Credentials, error)
- }
- func (f *FakeCredProvider) Retrieve(ctx context.Context) (aws.Credentials, error) {
- return f.retrieveFunc()
- }
- func (f *FakeCredProvider) IsExpired() bool {
- return true
- }
|