github.com/kyma-project/kyma-environment-broker@v0.0.1/internal/process/provisioning/inject_btp_operator_credentials_step_test.go (about)

     1  package provisioning
     2  
     3  import (
     4  	"context"
     5  	"reflect"
     6  	"testing"
     7  
     8  	btpoperatorcredentials "github.com/kyma-project/kyma-environment-broker/internal/btpmanager/credentials"
     9  
    10  	"github.com/kyma-project/kyma-environment-broker/internal"
    11  	"github.com/kyma-project/kyma-environment-broker/internal/fixture"
    12  	"github.com/kyma-project/kyma-environment-broker/internal/storage"
    13  	"github.com/pivotal-cf/brokerapi/v8/domain"
    14  	"github.com/sirupsen/logrus"
    15  	"github.com/stretchr/testify/assert"
    16  	"github.com/stretchr/testify/require"
    17  	apicorev1 "k8s.io/api/core/v1"
    18  	apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
    19  	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
    20  	"sigs.k8s.io/controller-runtime/pkg/client"
    21  	"sigs.k8s.io/controller-runtime/pkg/client/fake"
    22  )
    23  
    24  func TestInjectBTPOperatorCredentialsStep(t *testing.T) {
    25  	t.Run("should execute step flawlessly", func(t *testing.T) {
    26  		// given
    27  		log := logrus.New()
    28  		memoryStorage := storage.NewMemoryStorage()
    29  
    30  		scheme := internal.NewSchemeForTests()
    31  		err := apiextensionsv1.AddToScheme(scheme)
    32  
    33  		k8sClient := fake.NewClientBuilder().WithScheme(scheme).Build()
    34  
    35  		operation := fixProvisioningOperationWithClusterIDAndCredentials(k8sClient)
    36  		expectedSecretData := createExpectedSecretData(operation.ProvisioningParameters.ErsContext.SMOperatorCredentials, operation.ServiceManagerClusterID)
    37  
    38  		step := NewInjectBTPOperatorCredentialsStep(memoryStorage.Operations(), func(k string) (client.Client, error) { return k8sClient, nil })
    39  
    40  		// when
    41  		entry := log.WithFields(logrus.Fields{"step": "TEST"})
    42  		_, _, err = step.Run(operation, entry)
    43  
    44  		// then
    45  		assert.NoError(t, err)
    46  		assertTheNamespaceIsPresent(t, k8sClient)
    47  		assertTheSecretIsAsExpected(t, k8sClient, expectedSecretData)
    48  
    49  		// when
    50  		operation.ProvisioningParameters.ErsContext.SMOperatorCredentials.ClientSecret = "rotated-sample-client-secret"
    51  		expectedRotatedSecretData := createExpectedSecretData(operation.ProvisioningParameters.ErsContext.SMOperatorCredentials, operation.ServiceManagerClusterID)
    52  		_, _, err = step.Run(operation, entry)
    53  
    54  		// then
    55  		assert.NoError(t, err)
    56  		assertTheSecretIsAsExpected(t, k8sClient, expectedRotatedSecretData)
    57  	})
    58  	t.Run("should fail when RuntimeID is empty", func(t *testing.T) {
    59  		// given
    60  		log := logrus.New()
    61  		memoryStorage := storage.NewMemoryStorage()
    62  
    63  		scheme := internal.NewSchemeForTests()
    64  		apiextensionsv1.AddToScheme(scheme)
    65  
    66  		k8sClient := fake.NewClientBuilder().WithScheme(scheme).Build()
    67  
    68  		operation := fixture.FixProvisioningOperation("operation-id", "inst-id")
    69  		operation.RuntimeID = ""
    70  
    71  		step := NewInjectBTPOperatorCredentialsStep(memoryStorage.Operations(), func(k string) (client.Client, error) { return k8sClient, nil })
    72  
    73  		// when
    74  		entry := log.WithFields(logrus.Fields{"step": "TEST"})
    75  		processedOperation, _, _ := step.Run(operation, entry)
    76  
    77  		// then
    78  		assert.Equal(t, domain.Failed, processedOperation.State)
    79  	})
    80  }
    81  
    82  func TestInjectBTPOperatorCredentialsWhenSecretAlreadyExistsStep(t *testing.T) {
    83  	t.Run("should overwrite secret created by user", func(t *testing.T) {
    84  		// given
    85  		log := logrus.New()
    86  		memoryStorage := storage.NewMemoryStorage()
    87  
    88  		userSecret := &unstructured.Unstructured{Object: map[string]interface{}{
    89  			"apiVersion": "v1",
    90  			"kind":       "Secret",
    91  			"metadata": map[string]interface{}{
    92  				"name":      "sap-btp-manager",
    93  				"namespace": "kyma-system",
    94  			},
    95  		}}
    96  
    97  		scheme := internal.NewSchemeForTests()
    98  		err := apiextensionsv1.AddToScheme(scheme)
    99  
   100  		k8sClient := fake.NewClientBuilder().WithScheme(scheme).Build()
   101  
   102  		err = k8sClient.Create(context.TODO(), userSecret)
   103  
   104  		require.NoError(t, err)
   105  
   106  		operation := fixProvisioningOperationWithClusterIDAndCredentials(k8sClient)
   107  		expectedSecretData := createExpectedSecretData(operation.ProvisioningParameters.ErsContext.SMOperatorCredentials, operation.ServiceManagerClusterID)
   108  
   109  		step := NewInjectBTPOperatorCredentialsStep(memoryStorage.Operations(), func(k string) (client.Client, error) { return k8sClient, nil })
   110  
   111  		// when
   112  		entry := log.WithFields(logrus.Fields{"step": "TEST"})
   113  		_, _, err = step.Run(operation, entry)
   114  
   115  		// then
   116  		assert.NoError(t, err)
   117  		assertTheSecretIsAsExpected(t, k8sClient, expectedSecretData)
   118  	})
   119  }
   120  
   121  func fixProvisioningOperationWithClusterIDAndCredentials(k8sClient client.WithWatch) internal.Operation {
   122  	operation := fixProvisioningOperationWithCredentials(k8sClient)
   123  	operation.InstanceDetails.ServiceManagerClusterID = "cluster-id"
   124  	return operation
   125  }
   126  
   127  func fixProvisioningOperationWithCredentials(k8sClient client.WithWatch) internal.Operation {
   128  	operation := fixture.FixProvisioningOperation("operation-id", "inst-id")
   129  	operation.K8sClient = k8sClient
   130  	operation.ProvisioningParameters.ErsContext.SMOperatorCredentials = &internal.ServiceManagerOperatorCredentials{
   131  		ClientID:          "sample-client-id",
   132  		ClientSecret:      "sample-client-secret",
   133  		ServiceManagerURL: "www.service.manager.url.com",
   134  		URL:               "www.sample.url.com",
   135  		XSAppName:         "sample-app-name",
   136  	}
   137  	return operation
   138  }
   139  
   140  func assertTheSecretIsAsExpected(t *testing.T, k8sClient client.WithWatch, expected map[string][]byte) {
   141  	secretFromCluster := apicorev1.Secret{}
   142  	err := k8sClient.Get(context.Background(), client.ObjectKey{Namespace: btpoperatorcredentials.BtpManagerSecretNamespace, Name: btpoperatorcredentials.BtpManagerSecretName}, &secretFromCluster)
   143  	require.NoError(t, err)
   144  	assert.True(t, reflect.DeepEqual(expected, secretFromCluster.Data))
   145  	assert.True(t, reflect.DeepEqual(btpoperatorcredentials.BtpManagerLabels, secretFromCluster.Labels))
   146  	assert.True(t, reflect.DeepEqual(btpoperatorcredentials.BtpManagerAnnotations, secretFromCluster.Annotations))
   147  }
   148  
   149  func assertTheNamespaceIsPresent(t *testing.T, k8sClient client.WithWatch) {
   150  	namespace := apicorev1.Namespace{}
   151  	err := k8sClient.Get(context.Background(), client.ObjectKey{Name: btpoperatorcredentials.BtpManagerSecretNamespace}, &namespace)
   152  	require.NoError(t, err)
   153  }
   154  
   155  func createExpectedSecretData(credentials *internal.ServiceManagerOperatorCredentials, clusterID string) map[string][]byte {
   156  	return map[string][]byte{
   157  		"clientid":     []byte(credentials.ClientID),
   158  		"clientsecret": []byte(credentials.ClientSecret),
   159  		"sm_url":       []byte(credentials.ServiceManagerURL),
   160  		"tokenurl":     []byte(credentials.URL),
   161  		"cluster_id":   []byte(clusterID),
   162  	}
   163  }