diff --git a/controller/konnect/reconciler_konnectapiauth.go b/controller/konnect/reconciler_konnectapiauth.go index d1a711bbe..07b84bf6d 100644 --- a/controller/konnect/reconciler_konnectapiauth.go +++ b/controller/konnect/reconciler_konnectapiauth.go @@ -3,6 +3,8 @@ package konnect import ( "context" "fmt" + "regexp" + "strings" "time" sdkkonnectgoops "github.com/Kong/sdk-konnect-go/models/operations" @@ -129,8 +131,12 @@ func (r *KonnectAPIAuthConfigurationReconciler) Reconcile( return ctrl.Result{}, err } + serverURL, err := getKonnectServerURL(apiAuth.Spec.ServerURL) + if err != nil { + return ctrl.Result{}, err + } sdk := r.SDKFactory.NewKonnectSDK( - "https://"+apiAuth.Spec.ServerURL, + serverURL, SDKToken(token), ) @@ -244,3 +250,14 @@ func getTokenFromKonnectAPIAuthConfiguration( return "", fmt.Errorf("unknown KonnectAPIAuthType: %s", apiAuth.Spec.Type) } + +var serverURLRegexp = regexp.MustCompile(".*://") + +func getKonnectServerURL(serverURL string) (string, error) { + if !serverURLRegexp.MatchString(serverURL) { + serverURL = "https://" + serverURL + } else if !strings.HasPrefix(serverURL, "https://") { + return "", fmt.Errorf("in case scheme is specified in the ServerURL, it must be https://: %s", serverURL) + } + return serverURL, nil +} diff --git a/controller/konnect/reconciler_konnectapiauth_test.go b/controller/konnect/reconciler_konnectapiauth_test.go index 193d6d9dd..a5b482daa 100644 --- a/controller/konnect/reconciler_konnectapiauth_test.go +++ b/controller/konnect/reconciler_konnectapiauth_test.go @@ -2,6 +2,7 @@ package konnect import ( "context" + "errors" "testing" "github.com/stretchr/testify/assert" @@ -159,3 +160,39 @@ func TestGetTokenFromKonnectAPIAuthConfiguration(t *testing.T) { }) } } + +func TestGetKonnectServerURL(t *testing.T) { + var testCases = []struct { + name string + serverURL string + expectedServerURL string + expectedError error + }{ + { + name: "valid Server URL, with scheme", + serverURL: "https://konghq.com", + expectedServerURL: "https://konghq.com", + }, + { + name: "valid Server URL, without scheme", + serverURL: "konghq.com", + expectedServerURL: "https://konghq.com", + }, + { + name: "invalid Server URL", + serverURL: "http://konghq.com", + expectedServerURL: "", + expectedError: errors.New("in case scheme is specified in the ServerURL, it must be https://: http://konghq.com"), + }, + } + + for _, tc := range testCases { + tc := tc + t.Run(tc.name, func(t *testing.T) { + serverURL, err := getKonnectServerURL(tc.serverURL) + + assert.Equal(t, tc.expectedError, err) + assert.Equal(t, tc.expectedServerURL, serverURL) + }) + } +}