/*
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

    http://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 keyvault

import (
	"context"
	"encoding/base64"
	"encoding/json"
	"errors"
	"fmt"
	"reflect"
	"testing"
	"time"

	"github.com/Azure/azure-sdk-for-go/services/keyvault/v7.0/keyvault"
	"github.com/Azure/go-autorest/autorest"
	"github.com/Azure/go-autorest/autorest/date"
	"gopkg.in/yaml.v2"
	corev1 "k8s.io/api/core/v1"
	apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
	pointer "k8s.io/utils/ptr"

	esv1beta1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1beta1"
	v1 "github.com/external-secrets/external-secrets/apis/meta/v1"
	"github.com/external-secrets/external-secrets/pkg/provider/azure/keyvault/fake"
	testingfake "github.com/external-secrets/external-secrets/pkg/provider/testing/fake"
	"github.com/external-secrets/external-secrets/pkg/utils"
	"github.com/external-secrets/external-secrets/pkg/utils/metadata"
)

type secretManagerTestCase struct {
	mockClient              *fake.AzureMockClient
	secretName              string
	secretVersion           string
	serviceURL              string
	ref                     *esv1beta1.ExternalSecretDataRemoteRef
	refFind                 *esv1beta1.ExternalSecretFind
	apiErr                  error
	setErr                  error
	deleteErr               error
	pushData                esv1beta1.PushSecretData
	secretOutput            keyvault.SecretBundle
	setSecretOutput         keyvault.SecretBundle
	keyOutput               keyvault.KeyBundle
	createKeyOutput         keyvault.KeyBundle
	certOutput              keyvault.CertificateBundle
	importOutput            keyvault.CertificateBundle
	listOutput              keyvault.SecretListResultIterator
	deleteKeyOutput         keyvault.DeletedKeyBundle
	deleteCertificateOutput keyvault.DeletedCertificateBundle
	deleteSecretOutput      keyvault.DeletedSecretBundle

	expectError    string
	setValue       []byte
	expectedSecret string
	// for testing secretmap
	expectedData      map[string][]byte
	expectedExistence bool
	// for testing pushing multi-key k8s secrets
	secret *corev1.Secret
	// for testing changes in expiration date for akv secrets
	newExpiry *date.UnixTime
}

func makeValidSecretManagerTestCase() *secretManagerTestCase {
	secretString := "Hello World!"
	smtc := secretManagerTestCase{
		mockClient:     &fake.AzureMockClient{},
		secretName:     "MySecret",
		secretVersion:  "",
		ref:            makeValidRef(),
		refFind:        makeValidFind(),
		secretOutput:   keyvault.SecretBundle{Value: &secretString},
		serviceURL:     "",
		apiErr:         nil,
		expectError:    "",
		expectedSecret: secretString,
		expectedData:   map[string][]byte{},
	}

	smtc.mockClient.WithValue(smtc.serviceURL, smtc.secretName, smtc.secretVersion, smtc.secretOutput, smtc.apiErr)

	return &smtc
}

func makeValidSecretManagerTestCaseCustom(tweaks ...func(smtc *secretManagerTestCase)) *secretManagerTestCase {
	smtc := makeValidSecretManagerTestCase()
	for _, fn := range tweaks {
		fn(smtc)
	}

	smtc.mockClient.WithValue(smtc.serviceURL, smtc.secretName, smtc.secretVersion, smtc.secretOutput, smtc.apiErr)
	smtc.mockClient.WithKey(smtc.serviceURL, smtc.secretName, smtc.secretVersion, smtc.keyOutput, smtc.apiErr)
	smtc.mockClient.WithCertificate(smtc.serviceURL, smtc.secretName, smtc.secretVersion, smtc.certOutput, smtc.apiErr)
	smtc.mockClient.WithList(smtc.serviceURL, smtc.listOutput, smtc.apiErr)
	smtc.mockClient.WithImportCertificate(smtc.importOutput, smtc.setErr)
	smtc.mockClient.WithImportKey(smtc.createKeyOutput, smtc.setErr)
	smtc.mockClient.WithSetSecret(smtc.setSecretOutput, smtc.setErr)
	smtc.mockClient.WithDeleteCertificate(smtc.deleteCertificateOutput, smtc.deleteErr)
	smtc.mockClient.WithDeleteKey(smtc.deleteKeyOutput, smtc.deleteErr)
	smtc.mockClient.WithDeleteSecret(smtc.deleteSecretOutput, smtc.deleteErr)
	return smtc
}

const (
	jwkPubRSA            = `{"kid":"ex","kty":"RSA","key_ops":["sign","verify","wrapKey","unwrapKey","encrypt","decrypt"],"n":"p2VQo8qCfWAZmdWBVaYuYb-a-tWWm78K6Sr9poCvNcmv8rUPSLACxitQWR8gZaSH1DklVkqz-Ed8Cdlf8lkDg4Ex5tkB64jRdC1Uvn4CDpOH6cp-N2s8hTFLqy9_YaDmyQS7HiqthOi9oVjil1VMeWfaAbClGtFt6UnKD0Vb_DvLoWYQSqlhgBArFJi966b4E1pOq5Ad02K8pHBDThlIIx7unibLehhDU6q3DCwNH_OOLx6bgNtmvGYJDd1cywpkLQ3YzNCUPWnfMBJRP3iQP_WI21uP6cvo0DqBPBM4wvVzHbCT0vnIflwkbgEWkq1FprqAitZlop9KjLqzjp9vyQ","e":"AQAB"}`
	jwkPubEC             = `{"kid":"https://example.vault.azure.net/keys/ec-p-521/e3d0e9c179b54988860c69c6ae172c65","kty":"EC","key_ops":["sign","verify"],"crv":"P-521","x":"AedOAtb7H7Oz1C_cPKI_R4CN_eai5nteY6KFW07FOoaqgQfVCSkQDK22fCOiMT_28c8LZYJRsiIFz_IIbQUW7bXj","y":"AOnchHnmBphIWXvanmMAmcCDkaED6ycW8GsAl9fQ43BMVZTqcTkJYn6vGnhn7MObizmkNSmgZYTwG-vZkIg03HHs"}`
	jsonTestString       = `{"Name": "External", "LastName": "Secret", "Address": { "Street": "Myroad st.", "CP": "J4K4T4" } }`
	jsonSingleTestString = `{"Name": "External", "LastName": "Secret" }`
	jsonTagTestString    = `{"tagname":"tagvalue","tagname2":"tagvalue2"}`
	keyName              = "key/keyname"
	certName             = "cert/certname"
	secretString         = "changedvalue"
	unexpectedError      = "[%d] unexpected error: %s, expected: '%s'"
	unexpectedSecretData = "[%d] unexpected secret data: expected %#v, got %#v"
	errorNoTag           = "tag something does not exist"
	errNotManaged        = "not managed by external-secrets"
	errNoPermission      = "No Permissions"
	errAPI               = "unexpected api error"
	something            = "something"
	tagname              = "tagname"
	tagname2             = "tagname2"
	tagvalue             = "tagvalue"
	tagvalue2            = "tagvalue2"
	secretName           = "example-1"
	testsecret           = "test-secret"
	fakeURL              = "noop"
	foo                  = "foo"
	bar                  = "bar"
	errStore             = "Azure.ValidateStore() error = %v, wantErr %v"
	externalSecrets      = "external-secrets"
	notFoundMessage      = "Not Found"
	forbiddenMessage     = "Forbidden"
)

func getTagMap() map[string]*string {
	tag1 := "tagname"
	tag2 := "tagname2"
	value1 := "tagvalue"
	value2 := "tagvalue2"
	tagMap := make(map[string]*string)
	tagMap[tag1] = &value1
	tagMap[tag2] = &value2
	return tagMap
}

func newKVJWK(b []byte) *keyvault.JSONWebKey {
	var key keyvault.JSONWebKey
	err := json.Unmarshal(b, &key)
	if err != nil {
		panic(err)
	}
	return &key
}

func TestAzureKeyVaultDeleteSecret(t *testing.T) {
	unsupportedType := func(smtc *secretManagerTestCase) {
		smtc.pushData = testingfake.PushSecretData{
			RemoteKey: "yadayada/foo",
		}
		smtc.expectError = "secret type 'yadayada' is not supported"
	}

	secretSuccess := func(smtc *secretManagerTestCase) {
		smtc.pushData = testingfake.PushSecretData{
			RemoteKey: secretName,
		}
		smtc.secretOutput = keyvault.SecretBundle{
			Tags: map[string]*string{
				managedBy: pointer.To(externalSecrets),
			},
			Value: pointer.To("foo"),
		}
		smtc.deleteSecretOutput = keyvault.DeletedSecretBundle{}
	}

	secretNotFound := func(smtc *secretManagerTestCase) {
		smtc.pushData = testingfake.PushSecretData{
			RemoteKey: secretName,
		}
		smtc.apiErr = autorest.DetailedError{StatusCode: 404, Method: "GET", Message: notFoundMessage}
		smtc.deleteErr = autorest.DetailedError{StatusCode: 404, Method: "DELETE", Message: notFoundMessage}
	}

	secretNotManaged := func(smtc *secretManagerTestCase) {
		smtc.pushData = testingfake.PushSecretData{
			RemoteKey: secretName,
		}
		smtc.secretOutput = keyvault.SecretBundle{
			Value: pointer.To("foo"),
		}
		smtc.expectError = errNotManaged
		smtc.deleteErr = autorest.DetailedError{StatusCode: 500, Method: "DELETE", Message: "Shouldnt happen"}
	}

	secretUnexpectedError := func(smtc *secretManagerTestCase) {
		smtc.pushData = testingfake.PushSecretData{
			RemoteKey: secretName,
		}
		smtc.expectError = "boom"
		smtc.apiErr = errors.New("boom")
	}

	secretNoDeletePermissions := func(smtc *secretManagerTestCase) {
		smtc.pushData = testingfake.PushSecretData{
			RemoteKey: secretName,
		}
		smtc.secretOutput = keyvault.SecretBundle{
			Tags: map[string]*string{
				managedBy: pointer.To(externalSecrets),
			},
			Value: pointer.To("foo"),
		}
		smtc.expectError = errNoPermission
		smtc.deleteErr = autorest.DetailedError{StatusCode: 403, Method: "DELETE", Message: errNoPermission}
	}

	secretNoGetPermissions := func(smtc *secretManagerTestCase) {
		smtc.pushData = testingfake.PushSecretData{
			RemoteKey: secretName,
		}
		smtc.expectError = errNoPermission
		smtc.apiErr = autorest.DetailedError{StatusCode: 403, Method: "GET", Message: errNoPermission}
	}

	certificateSuccess := func(smtc *secretManagerTestCase) {
		smtc.pushData = testingfake.PushSecretData{
			RemoteKey: certName,
		}
		smtc.certOutput = keyvault.CertificateBundle{
			Tags: map[string]*string{
				managedBy: pointer.To(externalSecrets),
			},
		}
		smtc.deleteCertificateOutput = keyvault.DeletedCertificateBundle{}
	}
	certNotFound := func(smtc *secretManagerTestCase) {
		smtc.pushData = testingfake.PushSecretData{
			RemoteKey: certName,
		}
		smtc.apiErr = autorest.DetailedError{StatusCode: 404, Method: "GET", Message: "Certificate Not Found"}
		smtc.deleteErr = autorest.DetailedError{StatusCode: 404, Method: "DELETE", Message: notFoundMessage}
	}

	certNotManaged := func(smtc *secretManagerTestCase) {
		smtc.pushData = testingfake.PushSecretData{
			RemoteKey: certName,
		}
		smtc.certOutput = keyvault.CertificateBundle{}
		smtc.expectError = errNotManaged
		smtc.deleteErr = autorest.DetailedError{StatusCode: 500, Method: "DELETE", Message: "Shouldnt happen"}
	}

	certUnexpectedError := func(smtc *secretManagerTestCase) {
		smtc.pushData = testingfake.PushSecretData{
			RemoteKey: certName,
		}
		smtc.expectError = "crash"
		smtc.apiErr = errors.New("crash")
	}

	certNoDeletePermissions := func(smtc *secretManagerTestCase) {
		smtc.pushData = testingfake.PushSecretData{
			RemoteKey: certName,
		}
		smtc.certOutput = keyvault.CertificateBundle{
			Tags: map[string]*string{
				managedBy: pointer.To(externalSecrets),
			},
		}
		smtc.expectError = "No certificate delete Permissions"
		smtc.deleteErr = autorest.DetailedError{StatusCode: 403, Method: "DELETE", Message: "No certificate delete Permissions"}
	}

	certNoGetPermissions := func(smtc *secretManagerTestCase) {
		smtc.pushData = testingfake.PushSecretData{
			RemoteKey: certName,
		}
		smtc.expectError = "No certificate get Permissions"
		smtc.apiErr = autorest.DetailedError{StatusCode: 403, Method: "GET", Message: "No certificate get Permissions"}
	}

	keySuccess := func(smtc *secretManagerTestCase) {
		smtc.pushData = testingfake.PushSecretData{
			RemoteKey: keyName,
		}
		smtc.keyOutput = keyvault.KeyBundle{
			Tags: map[string]*string{
				managedBy: pointer.To(externalSecrets),
			},
		}
		smtc.deleteKeyOutput = keyvault.DeletedKeyBundle{}
	}
	keyNotFound := func(smtc *secretManagerTestCase) {
		smtc.pushData = testingfake.PushSecretData{
			RemoteKey: keyName,
		}
		smtc.apiErr = autorest.DetailedError{StatusCode: 404, Method: "GET", Message: notFoundMessage}
		smtc.deleteErr = autorest.DetailedError{StatusCode: 404, Method: "DELETE", Message: notFoundMessage}
	}

	keyNotManaged := func(smtc *secretManagerTestCase) {
		smtc.pushData = testingfake.PushSecretData{
			RemoteKey: keyName,
		}
		smtc.keyOutput = keyvault.KeyBundle{}
		smtc.expectError = errNotManaged
		smtc.deleteErr = autorest.DetailedError{StatusCode: 500, Method: "DELETE", Message: "Shouldnt happen"}
	}

	keyUnexpectedError := func(smtc *secretManagerTestCase) {
		smtc.pushData = testingfake.PushSecretData{
			RemoteKey: keyName,
		}
		smtc.expectError = "tls timeout"
		smtc.apiErr = errors.New("tls timeout")
	}

	keyNoDeletePermissions := func(smtc *secretManagerTestCase) {
		smtc.pushData = testingfake.PushSecretData{
			RemoteKey: keyName,
		}
		smtc.keyOutput = keyvault.KeyBundle{
			Tags: map[string]*string{
				managedBy: pointer.To(externalSecrets),
			},
		}
		smtc.expectError = errNoPermission
		smtc.deleteErr = autorest.DetailedError{StatusCode: 403, Method: "DELETE", Message: errNoPermission}
	}

	keyNoGetPermissions := func(smtc *secretManagerTestCase) {
		smtc.pushData = testingfake.PushSecretData{
			RemoteKey: keyName,
		}
		smtc.expectError = errNoPermission
		smtc.apiErr = autorest.DetailedError{StatusCode: 403, Method: "GET", Message: errNoPermission}
	}

	successCases := []*secretManagerTestCase{
		makeValidSecretManagerTestCaseCustom(unsupportedType),
		makeValidSecretManagerTestCaseCustom(secretSuccess),
		makeValidSecretManagerTestCaseCustom(secretNotFound),
		makeValidSecretManagerTestCaseCustom(secretNotManaged),
		makeValidSecretManagerTestCaseCustom(secretUnexpectedError),
		makeValidSecretManagerTestCaseCustom(secretNoDeletePermissions),
		makeValidSecretManagerTestCaseCustom(secretNoGetPermissions),
		makeValidSecretManagerTestCaseCustom(certificateSuccess),
		makeValidSecretManagerTestCaseCustom(certNotFound),
		makeValidSecretManagerTestCaseCustom(certNotManaged),
		makeValidSecretManagerTestCaseCustom(certUnexpectedError),
		makeValidSecretManagerTestCaseCustom(certNoDeletePermissions),
		makeValidSecretManagerTestCaseCustom(certNoGetPermissions),
		makeValidSecretManagerTestCaseCustom(keySuccess),
		makeValidSecretManagerTestCaseCustom(keyNotFound),
		makeValidSecretManagerTestCaseCustom(keyNotManaged),
		makeValidSecretManagerTestCaseCustom(keyUnexpectedError),
		makeValidSecretManagerTestCaseCustom(keyNoDeletePermissions),
		makeValidSecretManagerTestCaseCustom(keyNoGetPermissions),
	}

	sm := Azure{
		provider: &esv1beta1.AzureKVProvider{VaultURL: pointer.To(fakeURL)},
	}
	for k, v := range successCases {
		sm.baseClient = v.mockClient
		err := sm.DeleteSecret(context.Background(), v.pushData)
		if !utils.ErrorContains(err, v.expectError) {
			if err == nil {
				t.Errorf("[%d] unexpected error: <nil>, expected: '%s'", k, v.expectError)
			} else {
				t.Errorf("[%d] unexpected error: '%s', expected: '%s'", k, err.Error(), v.expectError)
			}
		}
	}
}
func TestAzureKeyVaultPushSecret(t *testing.T) {
	p12Cert, _ := base64.StdEncoding.DecodeString(" ")
	p12CertChainLegacy, _ := base64.StdEncoding.DecodeString(" ")
	p12CertChainModern, _ := base64.StdEncoding.DecodeString(" ")
	goodKey, _ := base64.StdEncoding.DecodeString(" ")
	goodSecret := "old"
	secretKey := "fakeSecretKey"
	typeNotSupported := func(smtc *secretManagerTestCase) {
		smtc.pushData = testingfake.PushSecretData{
			SecretKey: secretKey,
			RemoteKey: "badtype/secret",
		}
		smtc.expectError = "secret type badtype not supported"
	}
	secretSuccess := func(smtc *secretManagerTestCase) {
		smtc.setValue = []byte("secret")
		smtc.pushData = testingfake.PushSecretData{
			SecretKey: secretKey,
			RemoteKey: secretName,
		}
		smtc.secretOutput = keyvault.SecretBundle{
			Tags: map[string]*string{
				managedBy: pointer.To(externalSecrets),
			},
			Value: &goodSecret,
		}
	}
	secretNoChange := func(smtc *secretManagerTestCase) {
		smtc.setValue = []byte(goodSecret)
		smtc.pushData = testingfake.PushSecretData{
			SecretKey: secretKey,
			RemoteKey: secretName,
		}
		smtc.secretOutput = keyvault.SecretBundle{
			Tags: map[string]*string{
				managedBy: pointer.To(externalSecrets),
			},
			Value: &goodSecret,
		}
	}
	secretExpiryChange := func(smtc *secretManagerTestCase) {
		newExpiry := date.UnixTime(time.Now().Add(24 * time.Hour))
		oldExpiry := date.UnixTime(time.Now().Add(-1 * time.Hour))
		mdata := &metadata.PushSecretMetadata[PushSecretMetadataSpec]{
			APIVersion: metadata.APIVersion,
			Kind:       metadata.Kind,
			Spec: PushSecretMetadataSpec{
				ExpirationDate: time.Now().Add(24 * time.Hour).Format(time.RFC3339),
			},
		}
		metadataRaw, _ := yaml.Marshal(mdata)
		smtc.newExpiry = &newExpiry
		smtc.setValue = []byte(goodSecret)
		smtc.pushData = testingfake.PushSecretData{
			SecretKey: secretKey,
			RemoteKey: secretName,
			Metadata: &apiextensionsv1.JSON{
				Raw: metadataRaw,
			},
		}
		smtc.secretOutput = keyvault.SecretBundle{
			Tags: map[string]*string{
				managedBy: pointer.To(externalSecrets),
			},
			Value: &goodSecret,
			Attributes: &keyvault.SecretAttributes{
				Expires: &oldExpiry,
			},
		}
		smtc.setSecretOutput = keyvault.SecretBundle{
			Tags: map[string]*string{
				managedBy: pointer.To(externalSecrets),
			},
			Value: &goodSecret,
			Attributes: &keyvault.SecretAttributes{
				Expires: smtc.newExpiry,
			},
		}
	}
	secretWrongTags := func(smtc *secretManagerTestCase) {
		smtc.setValue = []byte(goodSecret)
		smtc.pushData = testingfake.PushSecretData{
			SecretKey: secretKey,
			RemoteKey: secretName,
		}
		smtc.secretOutput = keyvault.SecretBundle{
			Tags: map[string]*string{
				managedBy: pointer.To("nope"),
			},
			Value: &goodSecret,
		}
		smtc.expectError = errNotManaged
	}
	wholeSecretNoKey := func(smtc *secretManagerTestCase) {
		wholeSecretMap := map[string][]byte{"key1": []byte(`value1`), "key2": []byte(`value2`)}
		wholeSecretString := `{"key1": "value1", "key2": "value2" }`
		wholeSecret := &corev1.Secret{Data: wholeSecretMap}
		smtc.secret = wholeSecret
		smtc.pushData = testingfake.PushSecretData{
			RemoteKey: secretName,
		}
		smtc.secretOutput = keyvault.SecretBundle{
			Tags: map[string]*string{
				managedBy: pointer.To(externalSecrets),
			},
			Value: &wholeSecretString,
		}

		smtc.expectedData = wholeSecretMap
	}

	secretNoTags := func(smtc *secretManagerTestCase) {
		smtc.setValue = []byte(goodSecret)
		smtc.pushData = testingfake.PushSecretData{
			SecretKey: secretKey,
			RemoteKey: secretName,
		}
		smtc.secretOutput = keyvault.SecretBundle{
			Tags:  map[string]*string{},
			Value: &goodSecret,
		}
		smtc.expectError = errNotManaged
	}
	secretNotFound := func(smtc *secretManagerTestCase) {
		smtc.setValue = []byte(goodSecret)
		smtc.pushData = testingfake.PushSecretData{
			SecretKey: secretKey,
			RemoteKey: secretName,
		}
		smtc.apiErr = autorest.DetailedError{StatusCode: 404, Method: "GET", Message: notFoundMessage}
	}
	failedGetSecret := func(smtc *secretManagerTestCase) {
		smtc.setValue = []byte(goodSecret)
		smtc.pushData = testingfake.PushSecretData{
			SecretKey: secretKey,
			RemoteKey: secretName,
		}
		smtc.apiErr = autorest.DetailedError{StatusCode: 403, Method: "GET", Message: forbiddenMessage}
		smtc.expectError = errAPI
	}
	failedNotParseableError := func(smtc *secretManagerTestCase) {
		smtc.setValue = []byte(goodSecret)
		smtc.pushData = testingfake.PushSecretData{
			SecretKey: secretKey,
			RemoteKey: secretName,
		}
		smtc.apiErr = errors.New("crash")
		smtc.expectError = "crash"
	}
	failedSetSecret := func(smtc *secretManagerTestCase) {
		smtc.setValue = []byte(goodSecret)
		smtc.pushData = testingfake.PushSecretData{
			SecretKey: secretKey,
			RemoteKey: secretName,
		}
		smtc.apiErr = autorest.DetailedError{StatusCode: 404, Method: "GET", Message: notFoundMessage}
		smtc.setErr = autorest.DetailedError{StatusCode: 403, Method: "POST", Message: forbiddenMessage}
		smtc.expectError = "could not set secret example-1: #POST: Forbidden: StatusCode=403"
	}
	keySuccess := func(smtc *secretManagerTestCase) {
		smtc.setValue = goodKey
		smtc.pushData = testingfake.PushSecretData{
			SecretKey: secretKey,
			RemoteKey: keyName,
		}
		smtc.keyOutput = keyvault.KeyBundle{
			Tags: map[string]*string{
				managedBy: pointer.To(managerLabel),
			},
			Key: &keyvault.JSONWebKey{},
		}
	}
	symmetricKeySuccess := func(smtc *secretManagerTestCase) {
		smtc.setValue = []byte("secret")
		smtc.pushData = testingfake.PushSecretData{
			SecretKey: secretKey,
			RemoteKey: keyName,
		}
		smtc.keyOutput = keyvault.KeyBundle{
			Tags: map[string]*string{
				managedBy: pointer.To(managerLabel),
			},
			Key: &keyvault.JSONWebKey{},
		}
	}
	RSAKeySuccess := func(smtc *secretManagerTestCase) {
		smtc.setValue, _ = base64.StdEncoding.DecodeString(" ")
		smtc.pushData = testingfake.PushSecretData{
			SecretKey: secretKey,
			RemoteKey: keyName,
		}
		smtc.keyOutput = keyvault.KeyBundle{
			Tags: map[string]*string{
				managedBy: pointer.To(managerLabel),
			},
			Key: &keyvault.JSONWebKey{},
		}
	}
	ECKeySuccess := func(smtc *secretManagerTestCase) {
		smtc.setValue, _ = base64.StdEncoding.DecodeString("LS0tLS1CRUdJTiBFQyBQUklWQVRFIEtFWS0tLS0tCk1JR2tBZ0VCQkRBWTk0L0NYOGo4UDNBakZXUkZYR0pWMFNWT1ErU1ZpV01nd0VFdy9rV2ZXcHF1OGtidllVTnAKVTQyN1Fubk5NV3VnQndZRks0RUVBQ0toWkFOaUFBU1FyOXAvcytDWHpFY2RUZ2t0aVFhTkxuVzJnNmQ1QkF4cQpBQXNaQms2UW11WngrZTZMUUdra080Uit0SVVaZCtWTGJlV3pLeEl3dk9xSVA3bkp0QldtTjZ4N3JsMjJibnhNCm5QWVQyNy9wSXM1RTk1L2dPV2RhOGMyUStHQTd5RTQ9Ci0tLS0tRU5EIEVDIFBSSVZBVEUgS0VZLS0tLS0K")
		smtc.pushData = testingfake.PushSecretData{
			SecretKey: secretKey,
			RemoteKey: keyName,
		}
		smtc.keyOutput = keyvault.KeyBundle{
			Tags: map[string]*string{
				managedBy: pointer.To(managerLabel),
			},
			Key: &keyvault.JSONWebKey{},
		}
	}
	invalidKey := func(smtc *secretManagerTestCase) {
		smtc.setValue, _ = base64.StdEncoding.DecodeString("LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUZhekNDQTFPZ0F3SUJBZ0lVUHZKZ21wcTBKUWVRNkJuL0hmVTcvUDhRTFlFd0RRWUpLb1pJaHZjTkFRRUwKQlFBd1JURUxNQWtHQTFVRUJoTUNRVlV4RXpBUkJnTlZCQWdNQ2xOdmJXVXRVM1JoZEdVeElUQWZCZ05WQkFvTQpHRWx1ZEdWeWJtVjBJRmRwWkdkcGRITWdVSFI1SU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3hjaVlKU2lDdkZzR0hqYzBJaEtyTXBNCnFKRW03dWQxK3VTM3NHWTR6SkVUMUhleEJudjJ4RVlESjZhbGErV3FsNDdZTllSNm4yNlAvUWpNYjdSSGE1ZWMKUEhPMW5HaTY5L1U1dmVMRVlmZmtIV01qSTlKa1dhQzFiREcrMDl0clpSdXNUQWJCZHhqbWxzZ3o0UUFDeFd3PQotLS0tLUVORCBDRVJUSUZJQ0FURS0tLS0tCg==")
		smtc.pushData = testingfake.PushSecretData{
			SecretKey: secretKey,
			RemoteKey: keyName,
		}
		smtc.keyOutput = keyvault.KeyBundle{
			Tags: map[string]*string{
				managedBy: pointer.To(managerLabel),
			},
			Key: &keyvault.JSONWebKey{},
		}
		smtc.expectError = "could not load private key keyname: key type CERTIFICATE is not supported"
	}

	noTags := func(smtc *secretManagerTestCase) {
		smtc.setValue = goodKey
		smtc.pushData = testingfake.PushSecretData{
			SecretKey: secretKey,
			RemoteKey: keyName,
		}
		smtc.keyOutput = keyvault.KeyBundle{
			Tags: map[string]*string{},
			Key:  &keyvault.JSONWebKey{},
		}
		smtc.expectError = errNotManaged
	}
	wrongTags := func(smtc *secretManagerTestCase) {
		smtc.setValue = goodKey
		smtc.pushData = testingfake.PushSecretData{
			SecretKey: secretKey,
			RemoteKey: keyName,
		}
		smtc.keyOutput = keyvault.KeyBundle{
			Tags: map[string]*string{
				managedBy: pointer.To("internal-secrets"),
			},
			Key: &keyvault.JSONWebKey{},
		}
		smtc.expectError = errNotManaged
	}
	errorGetKey := func(smtc *secretManagerTestCase) {
		smtc.setValue = goodKey
		smtc.pushData = testingfake.PushSecretData{
			SecretKey: secretKey,
			RemoteKey: keyName,
		}
		smtc.apiErr = autorest.DetailedError{StatusCode: 403, Method: "GET", Message: forbiddenMessage}
		smtc.expectError = errAPI
	}
	keyNotFound := func(smtc *secretManagerTestCase) {
		smtc.setValue = goodKey
		smtc.pushData = testingfake.PushSecretData{
			SecretKey: secretKey,
			RemoteKey: keyName,
		}
		smtc.apiErr = autorest.DetailedError{StatusCode: 404, Method: "GET", Message: notFoundMessage}
		smtc.expectError = ""
	}
	importKeyFailed := func(smtc *secretManagerTestCase) {
		smtc.setValue = goodKey
		smtc.pushData = testingfake.PushSecretData{
			SecretKey: secretKey,
			RemoteKey: keyName,
		}
		smtc.apiErr = autorest.DetailedError{StatusCode: 404, Method: "GET", Message: notFoundMessage}
		smtc.setErr = autorest.DetailedError{StatusCode: 403, Method: "POST", Message: forbiddenMessage}
		smtc.expectError = "could not import key keyname: #POST: Forbidden: StatusCode=403"
	}
	certP12Success := func(smtc *secretManagerTestCase) {
		smtc.setValue = p12Cert
		smtc.pushData = testingfake.PushSecretData{
			SecretKey: secretKey,
			RemoteKey: certName,
		}
		smtc.certOutput = keyvault.CertificateBundle{
			X509Thumbprint: pointer.To("123"),
			Tags: map[string]*string{
				managedBy: pointer.To(externalSecrets),
			},
		}
	}
	certP12ChainLegacySuccess := func(smtc *secretManagerTestCase) {
		smtc.setValue = p12CertChainLegacy
		smtc.pushData = testingfake.PushSecretData{
			SecretKey: secretKey,
			RemoteKey: certName,
		}
		smtc.certOutput = keyvault.CertificateBundle{
			X509Thumbprint: pointer.To("123"),
			Tags: map[string]*string{
				managedBy: pointer.To(externalSecrets),
			},
		}
	}
	certP12ChainModernSuccess := func(smtc *secretManagerTestCase) {
		smtc.setValue = p12CertChainModern
		smtc.pushData = testingfake.PushSecretData{
			SecretKey: secretKey,
			RemoteKey: certName,
		}
		smtc.certOutput = keyvault.CertificateBundle{
			X509Thumbprint: pointer.To("123"),
			Tags: map[string]*string{
				managedBy: pointer.To(externalSecrets),
			},
		}
	}
	certPEMSuccess := func(smtc *secretManagerTestCase) {
		pemCert, _ := base64.StdEncoding.DecodeString("LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUZwekNDQTQrZ0F3SUJBZ0lVTUhhVDZtZG8vd2Urbit0NFB2R0JZaUdDSXE0d0RRWUpLb1pJaHZjTkFRRUwKQlFBd1l6RUxN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MmU0QitlYTByelFGWEFBVWpKNQpPWGFieGJEclErT01landjNEhxcXN4enRKZ0QyYVAyZUsyL0w1UFdQdWcwRSsxZzhBQlpmVmJvaC9NM01IZ2J6ClBnYVRxZ3V6R0Zka0czRVh1K09oR2JVMC8rNzdWTW5aaTJJUVpuL2F3R1VhN1grTVAwQkR2alZZNWtWcE1aMWgKYzJDbERqZ3hOc0xHdGlrTzRjV2I1c1FSUjJHWU0zZE1rNTBWUWN0SjVScXNSczZwT0NYRFhFM1JlVlFqNGhOQgplV3ZhRFdRMktteU9haTU1ZGJEcmxKK251ODNPbUNwNTlSelA1azU4WmFEWG5sQzM4VXdUdDBxMUQ3K3pGMHRzCjFHOTMydUVCSFdZSHVPQT0KLS0tLS1FTkQgQ0VSVElGSUNBVEUtLS0tLQo=")
		smtc.setValue = pemCert
		smtc.pushData = testingfake.PushSecretData{
			SecretKey: secretKey,
			RemoteKey: certName,
		}
		smtc.certOutput = keyvault.CertificateBundle{
			X509Thumbprint: pointer.To("123"),
			Tags: map[string]*string{
				managedBy: pointer.To(externalSecrets),
			},
		}
	}

	certPEMWithGarbageSuccess := func(smtc *secretManagerTestCase) {
		pemCert, _ := base64.StdEncoding.DecodeString(" ")
		smtc.setValue = pemCert
		smtc.pushData = testingfake.PushSecretData{
			SecretKey: secretKey,
			RemoteKey: certName,
		}
		smtc.certOutput = keyvault.CertificateBundle{
			X509Thumbprint: pointer.To("123"),
			Tags: map[string]*string{
				managedBy: pointer.To(externalSecrets),
			},
		}
	}

	certDERSuccess := func(smtc *secretManagerTestCase) {
		derCert, _ := base64.StdEncoding.DecodeString("MIIFpzCCA4+gAwIBAgIUMHaT6mdo/we+n+t4PvGBYiGCIq4wDQYJKoZIhvcNAQELBQAwYzELMAkGA1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoMGEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDEcMBoGA1UEAwwTYW5vdGhlci1mb28tYmFyLmNvbTAeFw0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107N9JuoKo2rr8hgmfFgt08+tSCc4yj6R5+rcXnuzjxFKibUbqgpZowJRHa21t5BbpL1yg2lfrfxHov/F8tVsSmA8wyh6UiWRwE9kvPWRnKnTukv5zzsqSlNSilm49zQ7SWNl+IAFy/swZrtJQ10VT9s4nPeG3oWQMotOPP+llSiynKLZqQ4gSKRi3fePLiWpt9XfXoGUCEj7q5phblLPgdKUCrhGP1n2jYmXscWLMykAna20chlrqVYnCa8JUp4LftFDp89YToXOFHnFmnNCvcIrDfFyDfhl4UMFpK0OUKqTTxWaK9uqOIparIsKYwsp+fLeWLbQ6kGfmnO5iDRd+oOhrNYooTZVK9fQR5rD2e4B+ea0rzQFXAAUjJ5OXabxbDrQ+OMejwc4HqqsxztJgD2aP2eK2/L5PWPug0E+1g8ABZfVboh/M3MHgbzPgaTqguzGFdkG3EXu+OhGbU0/+77VMnZi2IQZn/awGUa7X+MP0BDvjVY5kVpMZ1hc2ClDjgxNsLGtikO4cWb5sQRR2GYM3dMk50VQctJ5RqsRs6pOCXDXE3ReVQj4hNBeWvaDWQ2KmyOai55dbDrlJ+nu83OmCp59RzP5k58ZaDXnlC38UwTt0q1D7+zF0ts1G932uEBHWYHuOA=")
		smtc.setValue = derCert
		smtc.pushData = testingfake.PushSecretData{
			SecretKey: secretKey,
			RemoteKey: certName,
		}
		smtc.certOutput = keyvault.CertificateBundle{
			X509Thumbprint: pointer.To("123"),
			Tags: map[string]*string{
				managedBy: pointer.To(externalSecrets),
			},
		}
	}

	certImportCertificateError := func(smtc *secretManagerTestCase) {
		smtc.setErr = errors.New("error")
		smtc.setValue = p12Cert
		smtc.pushData = testingfake.PushSecretData{
			SecretKey: secretKey,
			RemoteKey: certName,
		}
		smtc.certOutput = keyvault.CertificateBundle{
			X509Thumbprint: pointer.To("123"),
			Tags: map[string]*string{
				managedBy: pointer.To(externalSecrets),
			},
		}
		smtc.expectError = "could not import certificate certname: error"
	}

	certFingerprintMatches := func(smtc *secretManagerTestCase) {
		smtc.setErr = errors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ELRJw1k8Gz3SaJoejhPsX/q73FYgAsOODpMrn+viSe4frfGEffQ/arTTNj+PTowIDAQABo1MwUTAdBgNVHQ4EFgQUbOBMxk2yRCdGSxxFF30TFNDXGKswHwYDVR0jBBgwFoAUbOBMxk2yRCdGSxxFF30TFNDXGKswDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAgEAAwnuKq98NChT2U3SdR4AUzmLN1BW04r0107N9JuoKo2rr8hgmfFgt08+tSCc4yj6R5+rcXnuzjxFKibUbqgpZowJRHa21t5BbpL1yg2lfrfxHov/F8tVsSmA8wyh6UiWRwE9kvPWRnKnTukv5zzsqSlNSilm49zQ7SWNl+IAFy/swZrtJQ10VT9s4nPeG3oWQMotOPP+llSiynKLZqQ4gSKRi3fePLiWpt9XfXoGUCEj7q5phblLPgdKUCrhGP1n2jYmXscWLMykAna20chlrqVYnCa8JUp4LftFDp89YToXOFHnFmnNCvcIrDfFyDfhl4UMFpK0OUKqTTxWaK9uqOIparIsKYwsp+fLeWLbQ6kGfmnO5iDRd+oOhrNYooTZVK9fQR5rD2e4B+ea0rzQFXAAUjJ5OXabxbDrQ+OMejwc4HqqsxztJgD2aP2eK2/L5PWPug0E+1g8ABZfVboh/M3MHgbzPgaTqguzGFdkG3EXu+OhGbU0/+77VMnZi2IQZn/awGUa7X+MP0BDvjVY5kVpMZ1hc2ClDjgxNsLGtikO4cWb5sQRR2GYM3dMk50VQctJ5RqsRs6pOCXDXE3ReVQj4hNBeWvaDWQ2KmyOai55dbDrlJ+nu83OmCp59RzP5k58ZaDXnlC38UwTt0q1D7+zF0ts1G932uEBHWYHuOA=")
		smtc.setValue = p12Cert
		smtc.pushData = testingfake.PushSecretData{
			SecretKey: secretKey,
			RemoteKey: certName,
		}
		smtc.certOutput = keyvault.CertificateBundle{
			Cer: &cert,
			Tags: map[string]*string{
				managedBy: pointer.To(externalSecrets),
			},
		}
	}

	certNotManagedByES := func(smtc *secretManagerTestCase) {
		smtc.setValue = p12Cert
		smtc.pushData = testingfake.PushSecretData{
			SecretKey: secretKey,
			RemoteKey: certName,
		}
		smtc.certOutput = keyvault.CertificateBundle{
			X509Thumbprint: pointer.To("123"),
			Tags: map[string]*string{
				managedBy: pointer.To("foobar"),
			},
		}
		smtc.expectError = "certificate certname: not managed by external-secrets"
	}

	certNoManagerTags := func(smtc *secretManagerTestCase) {
		smtc.setValue = p12Cert
		smtc.pushData = testingfake.PushSecretData{
			SecretKey: secretKey,
			RemoteKey: certName,
		}
		smtc.certOutput = keyvault.CertificateBundle{
			X509Thumbprint: pointer.To("123"),
		}
		smtc.expectError = "certificate certname: not managed by external-secrets"
	}

	certNotACertificate := func(smtc *secretManagerTestCase) {
		smtc.setValue = []byte("foobar")
		smtc.pushData = testingfake.PushSecretData{
			SecretKey: secretKey,
			RemoteKey: certName,
		}
		smtc.certOutput = keyvault.CertificateBundle{
			X509Thumbprint: pointer.To("123"),
		}
		smtc.expectError = "value from secret is not a valid certificate: could not parse certificate value as PKCS#12, DER or PEM"
	}

	certNoPermissions := func(smtc *secretManagerTestCase) {
		smtc.apiErr = autorest.DetailedError{
			StatusCode: 403,
			Method:     "GET",
			Message:    "Insufficient Permissions",
		}
		smtc.setValue = p12Cert
		smtc.pushData = testingfake.PushSecretData{
			SecretKey: secretKey,
			RemoteKey: certName,
		}
		smtc.certOutput = keyvault.CertificateBundle{
			X509Thumbprint: pointer.To("123"),
		}
		smtc.expectError = errAPI
	}

	successCases := []*secretManagerTestCase{
		makeValidSecretManagerTestCaseCustom(certP12Success),
		makeValidSecretManagerTestCaseCustom(certP12ChainLegacySuccess),
		makeValidSecretManagerTestCaseCustom(certP12ChainModernSuccess),
		makeValidSecretManagerTestCaseCustom(certPEMSuccess),
		makeValidSecretManagerTestCaseCustom(certPEMWithGarbageSuccess),
		makeValidSecretManagerTestCaseCustom(certDERSuccess),
		makeValidSecretManagerTestCaseCustom(certImportCertificateError),
		makeValidSecretManagerTestCaseCustom(certFingerprintMatches),
		makeValidSecretManagerTestCaseCustom(certNotManagedByES),
		makeValidSecretManagerTestCaseCustom(certNoManagerTags),
		makeValidSecretManagerTestCaseCustom(certNotACertificate),
		makeValidSecretManagerTestCaseCustom(certNoPermissions),
		makeValidSecretManagerTestCaseCustom(keySuccess),
		makeValidSecretManagerTestCaseCustom(symmetricKeySuccess),
		makeValidSecretManagerTestCaseCustom(RSAKeySuccess),
		makeValidSecretManagerTestCaseCustom(ECKeySuccess),
		makeValidSecretManagerTestCaseCustom(invalidKey),
		makeValidSecretManagerTestCaseCustom(errorGetKey),
		makeValidSecretManagerTestCaseCustom(keyNotFound),
		makeValidSecretManagerTestCaseCustom(importKeyFailed),
		makeValidSecretManagerTestCaseCustom(noTags),
		makeValidSecretManagerTestCaseCustom(wrongTags),
		makeValidSecretManagerTestCaseCustom(secretSuccess),
		makeValidSecretManagerTestCaseCustom(secretNoChange),
		makeValidSecretManagerTestCaseCustom(secretExpiryChange),
		makeValidSecretManagerTestCaseCustom(secretWrongTags),
		makeValidSecretManagerTestCaseCustom(secretNoTags),
		makeValidSecretManagerTestCaseCustom(secretNotFound),
		makeValidSecretManagerTestCaseCustom(failedGetSecret),
		makeValidSecretManagerTestCaseCustom(failedNotParseableError),
		makeValidSecretManagerTestCaseCustom(failedSetSecret),
		makeValidSecretManagerTestCaseCustom(typeNotSupported),
		makeValidSecretManagerTestCaseCustom(wholeSecretNoKey),
	}

	sm := Azure{
		provider: &esv1beta1.AzureKVProvider{VaultURL: pointer.To(fakeURL)},
	}
	for k, v := range successCases {
		sm.baseClient = v.mockClient
		if v.secret == nil {
			v.secret = &corev1.Secret{
				Data: map[string][]byte{
					secretKey: v.setValue,
				},
			}
		}
		err := sm.PushSecret(context.Background(), v.secret, v.pushData)
		if !utils.ErrorContains(err, v.expectError) {
			if err == nil {
				t.Errorf("[%d] unexpected error: <nil>, expected: '%s'", k, v.expectError)
			} else {
				t.Errorf(unexpectedError, k, err.Error(), v.expectError)
			}
		}
		if len(v.expectedData) > 0 {
			sm.baseClient = v.mockClient
			out, err := sm.GetSecretMap(context.Background(), *v.ref)
			if !utils.ErrorContains(err, v.expectError) {
				t.Errorf(unexpectedError, k, err.Error(), v.expectError)
			}
			if err == nil && !reflect.DeepEqual(out, v.expectedData) {
				t.Errorf(unexpectedSecretData, k, v.expectedData, out)
			}
		}
	}
}

// test the sm<->azurekv interface
// make sure correct values are passed and errors are handled accordingly.
func TestAzureKeyVaultSecretManagerGetSecret(t *testing.T) {
	secretString := "changedvalue"
	secretCertificate := "certificate_value"
	tagMap := getTagMap()

	// good case
	setSecretString := func(smtc *secretManagerTestCase) {
		smtc.expectedSecret = secretString
		smtc.secretOutput = keyvault.SecretBundle{
			Value: &secretString,
		}
	}
	// good case
	secretNotFound := func(smtc *secretManagerTestCase) {
		smtc.expectedSecret = ""
		smtc.apiErr = autorest.DetailedError{StatusCode: 404}
		smtc.expectError = esv1beta1.NoSecretError{}.Error()
	}

	certNotFound := func(smtc *secretManagerTestCase) {
		smtc.expectedSecret = ""
		smtc.secretName = certName
		smtc.apiErr = autorest.DetailedError{StatusCode: 404}
		smtc.expectError = esv1beta1.NoSecretError{}.Error()
	}

	keyNotFound := func(smtc *secretManagerTestCase) {
		smtc.expectedSecret = ""
		smtc.secretName = keyName
		smtc.apiErr = autorest.DetailedError{StatusCode: 404}
		smtc.expectError = esv1beta1.NoSecretError{}.Error()
	}

	setSecretStringWithVersion := func(smtc *secretManagerTestCase) {
		smtc.expectedSecret = secretString
		smtc.secretOutput = keyvault.SecretBundle{
			Value: &secretString,
		}
		smtc.ref.Version = "v1"
		smtc.secretVersion = smtc.ref.Version
	}

	setSecretWithProperty := func(smtc *secretManagerTestCase) {
		jsonString := jsonTestString
		smtc.expectedSecret = "External"
		smtc.secretOutput = keyvault.SecretBundle{
			Value: &jsonString,
		}
		smtc.ref.Property = "Name"
	}

	badSecretWithProperty := func(smtc *secretManagerTestCase) {
		jsonString := jsonTestString
		smtc.expectedSecret = ""
		smtc.secretOutput = keyvault.SecretBundle{
			Value: &jsonString,
		}
		smtc.ref.Property = "Age"
		smtc.expectError = fmt.Sprintf("property %s does not exist in key %s", smtc.ref.Property, smtc.ref.Key)
		smtc.apiErr = errors.New(smtc.expectError)
	}

	// // good case: key set
	setPubRSAKey := func(smtc *secretManagerTestCase) {
		smtc.secretName = keyName
		smtc.expectedSecret = jwkPubRSA
		smtc.keyOutput = keyvault.KeyBundle{
			Key: newKVJWK([]byte(jwkPubRSA)),
		}
		smtc.ref.Key = smtc.secretName
	}

	// // good case: key set
	setPubECKey := func(smtc *secretManagerTestCase) {
		smtc.secretName = keyName
		smtc.expectedSecret = jwkPubEC
		smtc.keyOutput = keyvault.KeyBundle{
			Key: newKVJWK([]byte(jwkPubEC)),
		}
		smtc.ref.Key = smtc.secretName
	}

	// // good case: key set
	setCertificate := func(smtc *secretManagerTestCase) {
		byteArrString := []byte(secretCertificate)
		smtc.secretName = certName
		smtc.expectedSecret = secretCertificate
		smtc.certOutput = keyvault.CertificateBundle{
			Cer: &byteArrString,
		}
		smtc.ref.Key = smtc.secretName
	}

	badSecretType := func(smtc *secretManagerTestCase) {
		smtc.secretName = "name"
		smtc.expectedSecret = ""
		smtc.expectError = fmt.Sprintf("unknown Azure Keyvault object Type for %s", smtc.secretName)
		smtc.ref.Key = fmt.Sprintf("example/%s", smtc.secretName)
	}

	setSecretWithTag := func(smtc *secretManagerTestCase) {
		smtc.ref.MetadataPolicy = esv1beta1.ExternalSecretMetadataPolicyFetch
		smtc.ref.Property = tagname
		smtc.secretOutput = keyvault.SecretBundle{
			Value: &secretString, Tags: tagMap,
		}
		smtc.expectedSecret = tagvalue
	}

	badSecretWithTag := func(smtc *secretManagerTestCase) {
		smtc.ref.MetadataPolicy = esv1beta1.ExternalSecretMetadataPolicyFetch
		smtc.ref.Property = something
		smtc.expectedSecret = ""
		smtc.expectError = errorNoTag
		smtc.apiErr = errors.New(smtc.expectError)
	}

	setSecretWithNoSpecificTag := func(smtc *secretManagerTestCase) {
		smtc.ref.MetadataPolicy = esv1beta1.ExternalSecretMetadataPolicyFetch
		smtc.secretOutput = keyvault.SecretBundle{
			Value: &secretString, Tags: tagMap,
		}
		smtc.expectedSecret = jsonTagTestString
	}

	setSecretWithNoTags := func(smtc *secretManagerTestCase) {
		smtc.ref.MetadataPolicy = esv1beta1.ExternalSecretMetadataPolicyFetch
		smtc.secretOutput = keyvault.SecretBundle{}
		smtc.expectedSecret = "{}"
	}

	setCertWithTag := func(smtc *secretManagerTestCase) {
		byteArrString := []byte(secretCertificate)
		smtc.secretName = certName
		smtc.certOutput = keyvault.CertificateBundle{
			Cer: &byteArrString, Tags: tagMap,
		}
		smtc.ref.MetadataPolicy = esv1beta1.ExternalSecretMetadataPolicyFetch
		smtc.ref.Property = tagname
		smtc.expectedSecret = tagvalue
		smtc.ref.Key = smtc.secretName
	}

	badCertWithTag := func(smtc *secretManagerTestCase) {
		byteArrString := []byte(secretCertificate)
		smtc.secretName = certName
		smtc.ref.Key = smtc.secretName
		smtc.certOutput = keyvault.CertificateBundle{
			Cer: &byteArrString,
		}
		smtc.ref.MetadataPolicy = esv1beta1.ExternalSecretMetadataPolicyFetch
		smtc.ref.Property = something
		smtc.expectedSecret = ""
		smtc.expectError = errorNoTag
		smtc.apiErr = errors.New(smtc.expectError)
	}

	setCertWithNoSpecificTag := func(smtc *secretManagerTestCase) {
		byteArrString := []byte(secretCertificate)
		smtc.secretName = certName
		smtc.ref.Key = smtc.secretName
		smtc.certOutput = keyvault.CertificateBundle{
			Cer: &byteArrString, Tags: tagMap,
		}
		smtc.ref.MetadataPolicy = esv1beta1.ExternalSecretMetadataPolicyFetch
		smtc.expectedSecret = jsonTagTestString
	}

	setCertWithNoTags := func(smtc *secretManagerTestCase) {
		byteArrString := []byte(secretCertificate)
		smtc.secretName = certName
		smtc.ref.Key = smtc.secretName
		smtc.certOutput = keyvault.CertificateBundle{
			Cer: &byteArrString,
		}
		smtc.ref.MetadataPolicy = esv1beta1.ExternalSecretMetadataPolicyFetch
		smtc.expectedSecret = "{}"
	}

	setKeyWithTag := func(smtc *secretManagerTestCase) {
		smtc.secretName = keyName
		smtc.keyOutput = keyvault.KeyBundle{
			Key: newKVJWK([]byte(jwkPubRSA)), Tags: tagMap,
		}
		smtc.ref.MetadataPolicy = esv1beta1.ExternalSecretMetadataPolicyFetch
		smtc.ref.Property = tagname
		smtc.expectedSecret = tagvalue
		smtc.ref.Key = smtc.secretName
	}

	badKeyWithTag := func(smtc *secretManagerTestCase) {
		smtc.secretName = keyName
		smtc.ref.Key = smtc.secretName
		smtc.keyOutput = keyvault.KeyBundle{
			Key: newKVJWK([]byte(jwkPubRSA)), Tags: tagMap,
		}
		smtc.ref.MetadataPolicy = esv1beta1.ExternalSecretMetadataPolicyFetch
		smtc.ref.Property = something
		smtc.expectedSecret = ""
		smtc.expectError = errorNoTag
		smtc.apiErr = errors.New(smtc.expectError)
	}

	setKeyWithNoSpecificTag := func(smtc *secretManagerTestCase) {
		smtc.secretName = keyName
		smtc.ref.Key = smtc.secretName
		smtc.keyOutput = keyvault.KeyBundle{
			Key: newKVJWK([]byte(jwkPubRSA)), Tags: tagMap,
		}
		smtc.ref.MetadataPolicy = esv1beta1.ExternalSecretMetadataPolicyFetch
		smtc.expectedSecret = jsonTagTestString
	}

	setKeyWithNoTags := func(smtc *secretManagerTestCase) {
		smtc.secretName = keyName
		smtc.ref.Key = smtc.secretName
		smtc.keyOutput = keyvault.KeyBundle{
			Key: newKVJWK([]byte(jwkPubRSA)),
		}
		smtc.ref.MetadataPolicy = esv1beta1.ExternalSecretMetadataPolicyFetch
		smtc.expectedSecret = "{}"
	}

	badPropertyTag := func(smtc *secretManagerTestCase) {
		smtc.ref.Property = tagname
		smtc.expectedSecret = ""
		smtc.expectError = "property tagname does not exist in key test-secret"
		smtc.apiErr = errors.New(smtc.expectError)
	}

	fetchSingleTag := func(smtc *secretManagerTestCase) {
		jsonString := jsonTestString
		smtc.expectedSecret = bar
		smtc.ref.MetadataPolicy = esv1beta1.ExternalSecretMetadataPolicyFetch
		secretTags := map[string]*string{}
		tagValue := bar
		secretTags[foo] = &tagValue
		smtc.secretOutput = keyvault.SecretBundle{
			Value: &jsonString,
			Tags:  secretTags,
		}
		smtc.ref.Property = foo
	}

	fetchJSONTag := func(smtc *secretManagerTestCase) {
		jsonString := jsonTestString
		smtc.ref.MetadataPolicy = esv1beta1.ExternalSecretMetadataPolicyFetch
		secretTags := map[string]*string{}
		tagValue := "{\"key\":\"value\"}"
		secretTags[foo] = &tagValue
		smtc.secretOutput = keyvault.SecretBundle{
			Value: &jsonString,
			Tags:  secretTags,
		}
		smtc.ref.Property = foo
		smtc.expectedSecret = tagValue
	}

	fetchDottedJSONTag := func(smtc *secretManagerTestCase) {
		jsonString := jsonTestString
		smtc.ref.MetadataPolicy = esv1beta1.ExternalSecretMetadataPolicyFetch
		secretTags := map[string]*string{}
		tagValue := "{\"key\":\"value\"}"
		secretTags[foo] = &tagValue
		smtc.secretOutput = keyvault.SecretBundle{
			Value: &jsonString,
			Tags:  secretTags,
		}
		smtc.ref.Property = "foo.key"
		smtc.expectedSecret = "value"
	}

	fetchNestedJSONTag := func(smtc *secretManagerTestCase) {
		jsonString := jsonTestString
		smtc.ref.MetadataPolicy = esv1beta1.ExternalSecretMetadataPolicyFetch
		secretTags := map[string]*string{}
		tagValue := "{\"key\":\"value\", \"nested\": {\"foo\":\"bar\"}}"
		secretTags["foo"] = &tagValue
		smtc.secretOutput = keyvault.SecretBundle{
			Value: &jsonString,
			Tags:  secretTags,
		}
		smtc.ref.Property = "foo.nested"
		smtc.expectedSecret = "{\"foo\":\"bar\"}"
	}

	fetchNestedDottedJSONTag := func(smtc *secretManagerTestCase) {
		jsonString := jsonTestString
		smtc.ref.MetadataPolicy = esv1beta1.ExternalSecretMetadataPolicyFetch
		secretTags := map[string]*string{}
		tagValue := "{\"key\":\"value\", \"nested\": {\"foo\":\"bar\"}}"
		secretTags[foo] = &tagValue
		smtc.secretOutput = keyvault.SecretBundle{
			Value: &jsonString,
			Tags:  secretTags,
		}
		smtc.ref.Property = "foo.nested.foo"
		smtc.expectedSecret = bar
	}

	fetchDottedKeyJSONTag := func(smtc *secretManagerTestCase) {
		jsonString := jsonTestString
		smtc.ref.MetadataPolicy = esv1beta1.ExternalSecretMetadataPolicyFetch
		secretTags := map[string]*string{}
		tagValue := "{\"foo.json\":\"bar\"}"
		secretTags[foo] = &tagValue
		smtc.secretOutput = keyvault.SecretBundle{
			Value: &jsonString,
			Tags:  secretTags,
		}
		smtc.ref.Property = "foo.foo.json"
		smtc.expectedSecret = bar
	}

	fetchDottedSecretJSONTag := func(smtc *secretManagerTestCase) {
		jsonString := "{\"foo.json\":\"bar\"}"
		smtc.secretOutput = keyvault.SecretBundle{
			Value: &jsonString,
		}
		smtc.ref.Property = "foo.json"
		smtc.expectedSecret = bar
	}

	successCases := []*secretManagerTestCase{
		makeValidSecretManagerTestCase(),
		makeValidSecretManagerTestCaseCustom(setSecretString),
		makeValidSecretManagerTestCaseCustom(setSecretStringWithVersion),
		makeValidSecretManagerTestCaseCustom(setSecretWithProperty),
		makeValidSecretManagerTestCaseCustom(badSecretWithProperty),
		makeValidSecretManagerTestCaseCustom(setPubRSAKey),
		makeValidSecretManagerTestCaseCustom(setPubECKey),
		makeValidSecretManagerTestCaseCustom(secretNotFound),
		makeValidSecretManagerTestCaseCustom(certNotFound),
		makeValidSecretManagerTestCaseCustom(keyNotFound),
		makeValidSecretManagerTestCaseCustom(setCertificate),
		makeValidSecretManagerTestCaseCustom(badSecretType),
		makeValidSecretManagerTestCaseCustom(setSecretWithTag),
		makeValidSecretManagerTestCaseCustom(badSecretWithTag),
		makeValidSecretManagerTestCaseCustom(setSecretWithNoSpecificTag),
		makeValidSecretManagerTestCaseCustom(setSecretWithNoTags),
		makeValidSecretManagerTestCaseCustom(setCertWithTag),
		makeValidSecretManagerTestCaseCustom(badCertWithTag),
		makeValidSecretManagerTestCaseCustom(setCertWithNoSpecificTag),
		makeValidSecretManagerTestCaseCustom(setCertWithNoTags),
		makeValidSecretManagerTestCaseCustom(setKeyWithTag),
		makeValidSecretManagerTestCaseCustom(badKeyWithTag),
		makeValidSecretManagerTestCaseCustom(setKeyWithNoSpecificTag),
		makeValidSecretManagerTestCaseCustom(setKeyWithNoTags),
		makeValidSecretManagerTestCaseCustom(badPropertyTag),
		makeValidSecretManagerTestCaseCustom(fetchSingleTag),
		makeValidSecretManagerTestCaseCustom(fetchJSONTag),
		makeValidSecretManagerTestCaseCustom(fetchDottedJSONTag),
		makeValidSecretManagerTestCaseCustom(fetchNestedJSONTag),
		makeValidSecretManagerTestCaseCustom(fetchNestedDottedJSONTag),
		makeValidSecretManagerTestCaseCustom(fetchDottedKeyJSONTag),
		makeValidSecretManagerTestCaseCustom(fetchDottedSecretJSONTag),
	}

	sm := Azure{
		provider: &esv1beta1.AzureKVProvider{VaultURL: pointer.To(fakeURL)},
	}
	for k, v := range successCases {
		sm.baseClient = v.mockClient
		out, err := sm.GetSecret(context.Background(), *v.ref)
		if !utils.ErrorContains(err, v.expectError) {
			t.Errorf(unexpectedError, k, err.Error(), v.expectError)
		}
		if string(out) != v.expectedSecret {
			t.Errorf("[%d] unexpected secret: expected %s, got %s", k, v.expectedSecret, string(out))
		}
	}
}

func TestAzureKeyVaultSecretManagerGetSecretMap(t *testing.T) {
	secretString := "changedvalue"
	secretCertificate := "certificate_value"
	tagMap := getTagMap()

	badSecretString := func(smtc *secretManagerTestCase) {
		smtc.expectedSecret = secretString
		smtc.secretOutput = keyvault.SecretBundle{
			Value: &secretString,
		}
		smtc.expectError = "error unmarshalling json data: invalid character 'c' looking for beginning of value"
	}

	setSecretJSON := func(smtc *secretManagerTestCase) {
		jsonString := jsonSingleTestString
		smtc.secretOutput = keyvault.SecretBundle{
			Value: &jsonString,
		}
		smtc.expectedData["Name"] = []byte("External")
		smtc.expectedData["LastName"] = []byte("Secret")
	}

	setSecretJSONWithProperty := func(smtc *secretManagerTestCase) {
		jsonString := jsonTestString
		smtc.secretOutput = keyvault.SecretBundle{
			Value: &jsonString,
		}
		smtc.ref.Property = "Address"

		smtc.expectedData["Street"] = []byte("Myroad st.")
		smtc.expectedData["CP"] = []byte("J4K4T4")
	}

	badSecretWithProperty := func(smtc *secretManagerTestCase) {
		jsonString := jsonTestString
		smtc.expectedSecret = ""
		smtc.secretOutput = keyvault.SecretBundle{
			Value: &jsonString,
		}
		smtc.ref.Property = "Age"
		smtc.expectError = fmt.Sprintf("property %s does not exist in key %s", smtc.ref.Property, smtc.ref.Key)
		smtc.apiErr = errors.New(smtc.expectError)
	}

	badPubRSAKey := func(smtc *secretManagerTestCase) {
		smtc.secretName = keyName
		smtc.expectedSecret = jwkPubRSA
		smtc.keyOutput = keyvault.KeyBundle{
			Key: newKVJWK([]byte(jwkPubRSA)),
		}
		smtc.ref.Key = smtc.secretName
		smtc.expectError = "cannot get use dataFrom to get key secret"
	}

	badCertificate := func(smtc *secretManagerTestCase) {
		byteArrString := []byte(secretCertificate)
		smtc.secretName = certName
		smtc.expectedSecret = secretCertificate
		smtc.certOutput = keyvault.CertificateBundle{
			Cer: &byteArrString,
		}
		smtc.ref.Key = smtc.secretName
		smtc.expectError = "cannot get use dataFrom to get certificate secret"
	}

	badSecretType := func(smtc *secretManagerTestCase) {
		smtc.secretName = "name"
		smtc.expectedSecret = ""
		smtc.expectError = fmt.Sprintf("unknown Azure Keyvault object Type for %s", smtc.secretName)
		smtc.ref.Key = fmt.Sprintf("example/%s", smtc.secretName)
	}

	setSecretTags := func(smtc *secretManagerTestCase) {
		smtc.ref.MetadataPolicy = esv1beta1.ExternalSecretMetadataPolicyFetch
		smtc.secretOutput = keyvault.SecretBundle{
			Tags: tagMap,
		}
		smtc.expectedData[testsecret+"_"+tagname] = []byte(tagvalue)
		smtc.expectedData[testsecret+"_"+tagname2] = []byte(tagvalue2)
	}

	setSecretWithJSONTag := func(smtc *secretManagerTestCase) {
		tagJSONMap := make(map[string]*string)
		tagJSONData := `{"keyname":"keyvalue","x":"y"}`
		tagJSONMap["json"] = &tagJSONData
		smtc.ref.MetadataPolicy = esv1beta1.ExternalSecretMetadataPolicyFetch
		smtc.secretOutput = keyvault.SecretBundle{
			Value: &secretString, Tags: tagJSONMap,
		}
		smtc.expectedData[testsecret+"_json_keyname"] = []byte("keyvalue")
		smtc.expectedData[testsecret+"_json_x"] = []byte("y")
	}

	setSecretWithNoTags := func(smtc *secretManagerTestCase) {
		smtc.ref.MetadataPolicy = esv1beta1.ExternalSecretMetadataPolicyFetch
		tagMapTestEmpty := make(map[string]*string)
		smtc.secretOutput = keyvault.SecretBundle{
			Tags: tagMapTestEmpty,
		}
		smtc.expectedSecret = ""
	}

	nestedJSONNoProperty := func(smtc *secretManagerTestCase) {
		jsonString := jsonTestString
		smtc.expectedSecret = ""
		smtc.secretOutput = keyvault.SecretBundle{
			Value: &jsonString,
		}
		smtc.ref.Property = ""
		smtc.expectedData["Name"] = []byte("External")
		smtc.expectedData["LastName"] = []byte("Secret")
		smtc.expectedData["Address"] = []byte(`{ "Street": "Myroad st.", "CP": "J4K4T4" }`)
	}

	setNestedJSONTag := func(smtc *secretManagerTestCase) {
		secretTags := map[string]*string{}
		tagValue := `{"foo":"bar","nested.tag":{"foo":"bar"}}`
		bug := "1137"
		secretTags["dev"] = &tagValue
		secretTags["bug"] = &bug

		smtc.ref.MetadataPolicy = esv1beta1.ExternalSecretMetadataPolicyFetch
		smtc.secretOutput = keyvault.SecretBundle{
			Tags: secretTags,
		}
		smtc.ref.Property = "dev"
		smtc.expectedData[testsecret+"_dev"] = []byte(tagValue)
	}

	successCases := []*secretManagerTestCase{
		makeValidSecretManagerTestCaseCustom(badSecretString),
		makeValidSecretManagerTestCaseCustom(setSecretJSON),
		makeValidSecretManagerTestCaseCustom(setSecretJSONWithProperty),
		makeValidSecretManagerTestCaseCustom(badSecretWithProperty),
		makeValidSecretManagerTestCaseCustom(badPubRSAKey),
		makeValidSecretManagerTestCaseCustom(badCertificate),
		makeValidSecretManagerTestCaseCustom(badSecretType),
		makeValidSecretManagerTestCaseCustom(setSecretTags),
		makeValidSecretManagerTestCaseCustom(setSecretWithJSONTag),
		makeValidSecretManagerTestCaseCustom(setSecretWithNoTags),
		makeValidSecretManagerTestCaseCustom(nestedJSONNoProperty),
		makeValidSecretManagerTestCaseCustom(setNestedJSONTag),
	}

	sm := Azure{
		provider: &esv1beta1.AzureKVProvider{VaultURL: pointer.To(fakeURL)},
	}
	for k, v := range successCases {
		sm.baseClient = v.mockClient
		out, err := sm.GetSecretMap(context.Background(), *v.ref)
		if !utils.ErrorContains(err, v.expectError) {
			t.Errorf(unexpectedError, k, err.Error(), v.expectError)
		}
		if err == nil && !reflect.DeepEqual(out, v.expectedData) {
			t.Errorf(unexpectedSecretData, k, v.expectedData, out)
		}
	}
}

func TestAzureKeyVaultSecretManagerGetAllSecrets(t *testing.T) {
	secretString := secretString
	secretName := secretName
	wrongName := "not-valid"
	environment := "dev"
	author := "seb"
	enabled := true

	getNextPage := func(ctx context.Context, list keyvault.SecretListResult) (result keyvault.SecretListResult, err error) {
		return keyvault.SecretListResult{
			Value:    nil,
			NextLink: nil,
		}, nil
	}

	setOneSecretByName := func(smtc *secretManagerTestCase) {
		enabledAtt := keyvault.SecretAttributes{
			Enabled: &enabled,
		}
		secretItem := keyvault.SecretItem{
			ID:         &secretName,
			Attributes: &enabledAtt,
		}

		list := keyvault.SecretListResult{
			Value: &[]keyvault.SecretItem{secretItem},
		}

		resultPage := keyvault.NewSecretListResultPage(list, getNextPage)
		smtc.listOutput = keyvault.NewSecretListResultIterator(resultPage)

		smtc.expectedSecret = secretString
		smtc.secretOutput = keyvault.SecretBundle{
			Value: &secretString,
		}

		smtc.expectedData[secretName] = []byte(secretString)
	}

	setTwoSecretsByName := func(smtc *secretManagerTestCase) {
		enabledAtt := keyvault.SecretAttributes{
			Enabled: &enabled,
		}
		secretItemOne := keyvault.SecretItem{
			ID:         &secretName,
			Attributes: &enabledAtt,
		}

		secretItemTwo := keyvault.SecretItem{
			ID:         &wrongName,
			Attributes: &enabledAtt,
		}

		list := keyvault.SecretListResult{
			Value: &[]keyvault.SecretItem{secretItemOne, secretItemTwo},
		}

		resultPage := keyvault.NewSecretListResultPage(list, getNextPage)
		smtc.listOutput = keyvault.NewSecretListResultIterator(resultPage)

		smtc.expectedSecret = secretString
		smtc.secretOutput = keyvault.SecretBundle{
			Value: &secretString,
		}

		smtc.expectedData[secretName] = []byte(secretString)
	}

	setOneSecretByTag := func(smtc *secretManagerTestCase) {
		enabledAtt := keyvault.SecretAttributes{
			Enabled: &enabled,
		}
		secretItem := keyvault.SecretItem{
			ID:         &secretName,
			Attributes: &enabledAtt,
			Tags:       map[string]*string{"environment": &environment},
		}

		list := keyvault.SecretListResult{
			Value: &[]keyvault.SecretItem{secretItem},
		}

		resultPage := keyvault.NewSecretListResultPage(list, getNextPage)
		smtc.listOutput = keyvault.NewSecretListResultIterator(resultPage)

		smtc.expectedSecret = secretString
		smtc.secretOutput = keyvault.SecretBundle{
			Value: &secretString,
		}
		smtc.refFind.Tags = map[string]string{"environment": environment}

		smtc.expectedData[secretName] = []byte(secretString)
	}

	setTwoSecretsByTag := func(smtc *secretManagerTestCase) {
		enabled := true
		enabledAtt := keyvault.SecretAttributes{
			Enabled: &enabled,
		}
		secretItem := keyvault.SecretItem{
			ID:         &secretName,
			Attributes: &enabledAtt,
			Tags:       map[string]*string{"environment": &environment, "author": &author},
		}

		list := keyvault.SecretListResult{
			Value: &[]keyvault.SecretItem{secretItem},
		}

		resultPage := keyvault.NewSecretListResultPage(list, getNextPage)
		smtc.listOutput = keyvault.NewSecretListResultIterator(resultPage)

		smtc.expectedSecret = secretString
		smtc.secretOutput = keyvault.SecretBundle{
			Value: &secretString,
		}
		smtc.refFind.Tags = map[string]string{"environment": environment, "author": author}

		smtc.expectedData[secretName] = []byte(secretString)
	}

	successCases := []*secretManagerTestCase{
		makeValidSecretManagerTestCaseCustom(setOneSecretByName),
		makeValidSecretManagerTestCaseCustom(setTwoSecretsByName),
		makeValidSecretManagerTestCaseCustom(setOneSecretByTag),
		makeValidSecretManagerTestCaseCustom(setTwoSecretsByTag),
	}

	sm := Azure{
		provider: &esv1beta1.AzureKVProvider{VaultURL: pointer.To(fakeURL)},
	}
	for k, v := range successCases {
		sm.baseClient = v.mockClient
		out, err := sm.GetAllSecrets(context.Background(), *v.refFind)
		if !utils.ErrorContains(err, v.expectError) {
			t.Errorf(unexpectedError, k, err.Error(), v.expectError)
		}
		if err == nil && !reflect.DeepEqual(out, v.expectedData) {
			t.Errorf(unexpectedSecretData, k, v.expectedData, out)
		}
	}
}

func makeValidRef() *esv1beta1.ExternalSecretDataRemoteRef {
	return &esv1beta1.ExternalSecretDataRemoteRef{
		Key:      "test-secret",
		Version:  "default",
		Property: "",
	}
}

func makeValidFind() *esv1beta1.ExternalSecretFind {
	return &esv1beta1.ExternalSecretFind{
		Name: &esv1beta1.FindName{
			RegExp: "^example",
		},
		Tags: map[string]string{},
	}
}

func TestValidateStore(t *testing.T) {
	type args struct {
		store *esv1beta1.SecretStore
	}
	tests := []struct {
		name    string
		args    args
		wantErr bool
	}{
		{
			name:    "storeIsNil",
			wantErr: true,
		},
		{
			name:    "specIsNil",
			wantErr: true,
			args: args{
				store: &esv1beta1.SecretStore{},
			},
		},
		{
			name:    "providerIsNil",
			wantErr: true,
			args: args{
				store: &esv1beta1.SecretStore{
					Spec: esv1beta1.SecretStoreSpec{},
				},
			},
		},
		{
			name:    "azureKVIsNil",
			wantErr: true,
			args: args{
				store: &esv1beta1.SecretStore{
					Spec: esv1beta1.SecretStoreSpec{
						Provider: &esv1beta1.SecretStoreProvider{},
					},
				},
			},
		},
		{
			name:    "empty auth",
			wantErr: false,
			args: args{
				store: &esv1beta1.SecretStore{
					Spec: esv1beta1.SecretStoreSpec{
						Provider: &esv1beta1.SecretStoreProvider{
							AzureKV: &esv1beta1.AzureKVProvider{},
						},
					},
				},
			},
		},
		{
			name:    "empty client id",
			wantErr: false,
			args: args{
				store: &esv1beta1.SecretStore{
					Spec: esv1beta1.SecretStoreSpec{
						Provider: &esv1beta1.SecretStoreProvider{
							AzureKV: &esv1beta1.AzureKVProvider{
								AuthSecretRef: &esv1beta1.AzureKVAuth{},
							},
						},
					},
				},
			},
		},
		{
			name:    "invalid client id",
			wantErr: true,
			args: args{
				store: &esv1beta1.SecretStore{
					Spec: esv1beta1.SecretStoreSpec{
						Provider: &esv1beta1.SecretStoreProvider{
							AzureKV: &esv1beta1.AzureKVProvider{
								AuthSecretRef: &esv1beta1.AzureKVAuth{
									ClientID: &v1.SecretKeySelector{
										Namespace: pointer.To("invalid"),
									},
								},
							},
						},
					},
				},
			},
		},
		{
			name:    "invalid client secret",
			wantErr: true,
			args: args{
				store: &esv1beta1.SecretStore{
					Spec: esv1beta1.SecretStoreSpec{
						Provider: &esv1beta1.SecretStoreProvider{
							AzureKV: &esv1beta1.AzureKVProvider{
								AuthSecretRef: &esv1beta1.AzureKVAuth{
									ClientSecret: &v1.SecretKeySelector{
										Namespace: pointer.To("invalid"),
									},
								},
							},
						},
					},
				},
			},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			a := &Azure{}
			if tt.name == "storeIsNil" {
				if _, err := a.ValidateStore(nil); (err != nil) != tt.wantErr {
					t.Errorf(errStore, err, tt.wantErr)
				}
			} else if _, err := a.ValidateStore(tt.args.store); (err != nil) != tt.wantErr {
				t.Errorf(errStore, err, tt.wantErr)
			}
		})
	}
}

func TestAzureKeyVaultSecretExists(t *testing.T) {
	unsupportedType := func(smtc *secretManagerTestCase) {
		smtc.pushData = testingfake.PushSecretData{
			RemoteKey: "yadayada/foo",
		}
		smtc.expectError = "secret type 'yadayada' is not supported"
	}

	secretFound := func(smtc *secretManagerTestCase) {
		smtc.pushData = testingfake.PushSecretData{
			RemoteKey: secretName,
		}
		smtc.secretOutput = keyvault.SecretBundle{
			Tags: map[string]*string{
				"managed-by": pointer.To(externalSecrets),
			},
			Value: pointer.To("foo"),
		}
		smtc.expectedExistence = true
	}

	secretFoundNoUsefulTags := func(smtc *secretManagerTestCase) {
		smtc.pushData = testingfake.PushSecretData{
			RemoteKey: secretName,
		}
		smtc.secretOutput = keyvault.SecretBundle{
			Tags: map[string]*string{
				"someTag": pointer.To("someUselessValue"),
			},
			Value: pointer.To("foo"),
		}
		smtc.expectedExistence = true
	}

	secretNotFound := func(smtc *secretManagerTestCase) {
		smtc.pushData = testingfake.PushSecretData{
			RemoteKey: secretName,
		}
		smtc.apiErr = autorest.DetailedError{StatusCode: 404, Method: "GET", Message: notFoundMessage}
		smtc.expectedExistence = false
	}

	testCases := []*secretManagerTestCase{
		makeValidSecretManagerTestCaseCustom(unsupportedType),
		makeValidSecretManagerTestCaseCustom(secretFound),
		makeValidSecretManagerTestCaseCustom(secretFoundNoUsefulTags),
		makeValidSecretManagerTestCaseCustom(secretNotFound),
	}

	sm := Azure{
		provider: &esv1beta1.AzureKVProvider{VaultURL: pointer.To(fakeURL)},
	}

	for k, tc := range testCases {
		sm.baseClient = tc.mockClient
		exists, err := sm.SecretExists(context.Background(), tc.pushData)

		if !utils.ErrorContains(err, tc.expectError) {
			if err == nil {
				t.Errorf("[%d] unexpected error: <nil>, expected: '%s'", k, tc.expectError)
			} else {
				t.Errorf("[%d] unexpected error: '%s', expected: '%s'", k, err.Error(), tc.expectError)
			}
		}

		if exists != tc.expectedExistence {
			t.Errorf("[%d] unexpected existence result: expected %t, got %t", k, tc.expectedExistence, exists)
		}
	}
}
