diff --git a/cmd/main.go b/cmd/main.go index 202273b5..06d02fdb 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -12,6 +12,7 @@ import ( "github.com/codeready-toolchain/registration-service/pkg/auth" "github.com/codeready-toolchain/registration-service/pkg/configuration" "github.com/codeready-toolchain/registration-service/pkg/log" + "github.com/codeready-toolchain/registration-service/pkg/namespaced" "github.com/codeready-toolchain/registration-service/pkg/proxy" "github.com/codeready-toolchain/registration-service/pkg/proxy/metrics" "github.com/codeready-toolchain/registration-service/pkg/server" @@ -83,8 +84,9 @@ func main() { panic(fmt.Sprintf("cannot set captcha credentials: %s", err.Error())) } } + nsClient := namespaced.NewClient(cl, configuration.Namespace()) - app := server.NewInClusterApplication(cl, configuration.Namespace()) + app := server.NewInClusterApplication(nsClient) // Initialize toolchain cluster cache service // let's cache the member clusters before we start the services, // this will speed up the first request @@ -106,7 +108,7 @@ func main() { proxyMetrics := metrics.NewProxyMetrics(proxyRegistry) proxyMetricsSrv := proxy.StartMetricsServer(proxyRegistry, proxy.ProxyMetricsPort) // Proxy API server - p, err := proxy.NewProxy(app, proxyMetrics, cluster.GetMemberClusters) + p, err := proxy.NewProxy(nsClient, app, proxyMetrics, cluster.GetMemberClusters) if err != nil { panic(errs.Wrap(err, "failed to create proxy")) } @@ -118,7 +120,7 @@ func main() { regsvcRegistry := prometheus.NewRegistry() regsvcMetricsSrv, _ := server.StartMetricsServer(regsvcRegistry, server.RegSvcMetricsPort) regsvcSrv := server.New(app) - err = regsvcSrv.SetupRoutes(proxy.DefaultPort, regsvcRegistry) + err = regsvcSrv.SetupRoutes(proxy.DefaultPort, regsvcRegistry, nsClient) if err != nil { panic(err.Error()) } diff --git a/pkg/application/service/factory/service_factory.go b/pkg/application/service/factory/service_factory.go index 67f947ba..65e46cdc 100644 --- a/pkg/application/service/factory/service_factory.go +++ b/pkg/application/service/factory/service_factory.go @@ -6,7 +6,6 @@ import ( "github.com/codeready-toolchain/registration-service/pkg/application/service" servicecontext "github.com/codeready-toolchain/registration-service/pkg/application/service/context" "github.com/codeready-toolchain/registration-service/pkg/configuration" - informerservice "github.com/codeready-toolchain/registration-service/pkg/informers/service" "github.com/codeready-toolchain/registration-service/pkg/log" "github.com/codeready-toolchain/registration-service/pkg/namespaced" clusterservice "github.com/codeready-toolchain/registration-service/pkg/proxy/service" @@ -52,10 +51,6 @@ func (s *ServiceFactory) defaultServiceContextProducer() servicecontext.ServiceC } } -func (s *ServiceFactory) InformerService() service.InformerService { - return informerservice.NewInformerService(s.getContext().Client(), configuration.Namespace()) -} - func (s *ServiceFactory) MemberClusterService() service.MemberClusterService { return clusterservice.NewMemberClusterService(s.getContext().Client(), s.getContext().Services().SignupService()) } diff --git a/pkg/application/service/services.go b/pkg/application/service/services.go index 4df4130f..2b8c2214 100644 --- a/pkg/application/service/services.go +++ b/pkg/application/service/services.go @@ -5,17 +5,8 @@ import ( "github.com/codeready-toolchain/registration-service/pkg/proxy/access" "github.com/codeready-toolchain/registration-service/pkg/signup" "github.com/gin-gonic/gin" - "k8s.io/apimachinery/pkg/labels" ) -type InformerService interface { - GetMasterUserRecord(name string) (*toolchainv1alpha1.MasterUserRecord, error) - GetSpace(name string) (*toolchainv1alpha1.Space, error) - ListSpaceBindings(reqs ...labels.Requirement) ([]toolchainv1alpha1.SpaceBinding, error) - GetNSTemplateTier(name string) (*toolchainv1alpha1.NSTemplateTier, error) - ListBannedUsersByEmail(email string) ([]toolchainv1alpha1.BannedUser, error) -} - type SignupService interface { Signup(ctx *gin.Context) (*toolchainv1alpha1.UserSignup, error) GetSignup(ctx *gin.Context, userID, username string) (*signup.Signup, error) @@ -25,10 +16,6 @@ type SignupService interface { PhoneNumberAlreadyInUse(userID, username, phoneNumberOrHash string) error } -type SocialEventService interface { - GetEvent(code string) (*toolchainv1alpha1.SocialEvent, error) -} - type VerificationService interface { InitVerification(ctx *gin.Context, userID, username, e164PhoneNumber, countryCode string) error VerifyPhoneCode(ctx *gin.Context, userID, username, code string) error @@ -40,7 +27,6 @@ type MemberClusterService interface { } type Services interface { - InformerService() InformerService SignupService() SignupService VerificationService() VerificationService MemberClusterService() MemberClusterService diff --git a/pkg/controller/usernames.go b/pkg/controller/usernames.go index 573f00d6..62a7dbe2 100644 --- a/pkg/controller/usernames.go +++ b/pkg/controller/usernames.go @@ -3,9 +3,10 @@ package controller import ( "net/http" - "github.com/codeready-toolchain/registration-service/pkg/application" + toolchainv1alpha1 "github.com/codeready-toolchain/api/api/v1alpha1" crterrors "github.com/codeready-toolchain/registration-service/pkg/errors" "github.com/codeready-toolchain/registration-service/pkg/log" + "github.com/codeready-toolchain/registration-service/pkg/namespaced" "github.com/codeready-toolchain/registration-service/pkg/username" "github.com/gin-gonic/gin" "k8s.io/apimachinery/pkg/api/errors" @@ -13,13 +14,13 @@ import ( // Usernames implements the usernames endpoint, which is invoked for checking if a given username/email exists. type Usernames struct { - app application.Application + namespaced.Client } // NewUsernames returns a new Usernames instance. -func NewUsernames(app application.Application) *Usernames { +func NewUsernames(nsClient namespaced.Client) *Usernames { return &Usernames{ - app: app, + Client: nsClient, } } @@ -34,7 +35,8 @@ func (s *Usernames) GetHandler(ctx *gin.Context) { // TODO check if the queryString is an email // in that case we have to fetch the UserSignup resources with the provided email and the MasterUserRecords associated with those. - murResource, err := s.app.InformerService().GetMasterUserRecord(queryString) + murResource := &toolchainv1alpha1.MasterUserRecord{} + err := s.Get(ctx.Request.Context(), s.NamespacedName(queryString), murResource) // handle not found error if errors.IsNotFound(err) { log.Infof(ctx, "MasterUserRecord resource for: %s not found", queryString) diff --git a/pkg/controller/usernames_test.go b/pkg/controller/usernames_test.go index 3fe507ff..2b5467ca 100644 --- a/pkg/controller/usernames_test.go +++ b/pkg/controller/usernames_test.go @@ -9,7 +9,7 @@ import ( "testing" "github.com/codeready-toolchain/registration-service/pkg/controller" - "github.com/codeready-toolchain/registration-service/pkg/informers/service" + "github.com/codeready-toolchain/registration-service/pkg/namespaced" "github.com/codeready-toolchain/registration-service/pkg/username" "github.com/codeready-toolchain/registration-service/test" "github.com/codeready-toolchain/registration-service/test/fake" @@ -40,11 +40,10 @@ func (s *TestUsernamesSuite) TestUsernamesGetHandler() { s.Run("success", func() { - fakeInformer := service.NewInformerService(fakeClient, commontest.HostOperatorNs) - s.Application.MockInformerService(fakeInformer) + nsClient := namespaced.NewClient(fakeClient, commontest.HostOperatorNs) // Create Usernames controller instance. - ctrl := controller.NewUsernames(s.Application) + ctrl := controller.NewUsernames(nsClient) handler := gin.HandlerFunc(ctrl.GetHandler) s.Run("usernames found", func() { @@ -104,11 +103,10 @@ func (s *TestUsernamesSuite) TestUsernamesGetHandler() { fakeClient.MockGet = func(_ context.Context, _ client.ObjectKey, _ client.Object, _ ...client.GetOption) error { return fmt.Errorf("mock error") } - fakeInformer := service.NewInformerService(fakeClient, commontest.HostOperatorNs) - s.Application.MockInformerService(fakeInformer) + nsClient := namespaced.NewClient(fakeClient, commontest.HostOperatorNs) // Create Usernames controller instance. - ctrl := controller.NewUsernames(s.Application) + ctrl := controller.NewUsernames(nsClient) handler := gin.HandlerFunc(ctrl.GetHandler) s.Run("unable to get mur", func() { // We create a ResponseRecorder (which satisfies http.ResponseWriter) to record the response. diff --git a/pkg/informers/service/informer_service.go b/pkg/informers/service/informer_service.go deleted file mode 100644 index 269d1952..00000000 --- a/pkg/informers/service/informer_service.go +++ /dev/null @@ -1,76 +0,0 @@ -package service - -import ( - "context" - - toolchainv1alpha1 "github.com/codeready-toolchain/api/api/v1alpha1" - "github.com/codeready-toolchain/registration-service/pkg/application/service" - "github.com/codeready-toolchain/toolchain-common/pkg/hash" - - "k8s.io/apimachinery/pkg/labels" - "k8s.io/apimachinery/pkg/types" - "sigs.k8s.io/controller-runtime/pkg/client" -) - -type Option func(f *ServiceImpl) - -// ServiceImpl represents the implementation of the informer service. -type ServiceImpl struct { // nolint:revive - client client.Client - namespace string -} - -// NewInformerService creates a service object for getting resources -func NewInformerService(client client.Client, namespace string) service.InformerService { - si := &ServiceImpl{ - client: client, - namespace: namespace, - } - return si -} - -func (s *ServiceImpl) GetMasterUserRecord(name string) (*toolchainv1alpha1.MasterUserRecord, error) { - mur := &toolchainv1alpha1.MasterUserRecord{} - namespacedName := types.NamespacedName{Name: name, Namespace: s.namespace} - err := s.client.Get(context.TODO(), namespacedName, mur) - return mur, err -} - -func (s *ServiceImpl) GetSpace(name string) (*toolchainv1alpha1.Space, error) { - space := &toolchainv1alpha1.Space{} - namespacedName := types.NamespacedName{Name: name, Namespace: s.namespace} - err := s.client.Get(context.TODO(), namespacedName, space) - return space, err -} - -func (s *ServiceImpl) ListSpaceBindings(reqs ...labels.Requirement) ([]toolchainv1alpha1.SpaceBinding, error) { - selector := labels.NewSelector() - for i := range reqs { - selector = selector.Add(reqs[i]) - } - - bindings := &toolchainv1alpha1.SpaceBindingList{} - if err := s.client.List(context.TODO(), bindings, client.InNamespace(s.namespace), client.MatchingLabelsSelector{Selector: selector}); err != nil { - return nil, err - } - return bindings.Items, nil -} - -func (s *ServiceImpl) GetNSTemplateTier(name string) (*toolchainv1alpha1.NSTemplateTier, error) { - tier := &toolchainv1alpha1.NSTemplateTier{} - namespacedName := types.NamespacedName{Name: name, Namespace: s.namespace} - err := s.client.Get(context.TODO(), namespacedName, tier) - return tier, err -} - -func (s *ServiceImpl) ListBannedUsersByEmail(email string) ([]toolchainv1alpha1.BannedUser, error) { - hashedEmail := hash.EncodeString(email) - - bannedUsers := &toolchainv1alpha1.BannedUserList{} - if err := s.client.List(context.TODO(), bannedUsers, client.InNamespace(s.namespace), - client.MatchingLabels{toolchainv1alpha1.BannedUserEmailHashLabelKey: hashedEmail}); err != nil { - return nil, err - } - - return bannedUsers.Items, nil -} diff --git a/pkg/informers/service/informer_service_test.go b/pkg/informers/service/informer_service_test.go deleted file mode 100644 index 832bf78e..00000000 --- a/pkg/informers/service/informer_service_test.go +++ /dev/null @@ -1,180 +0,0 @@ -package service_test - -import ( - "testing" - - toolchainv1alpha1 "github.com/codeready-toolchain/api/api/v1alpha1" - "github.com/codeready-toolchain/registration-service/pkg/informers/service" - "github.com/codeready-toolchain/toolchain-common/pkg/hash" - "github.com/codeready-toolchain/toolchain-common/pkg/test" - "github.com/codeready-toolchain/toolchain-common/pkg/test/masteruserrecord" - "github.com/codeready-toolchain/toolchain-common/pkg/test/space" - "github.com/codeready-toolchain/toolchain-common/pkg/test/usersignup" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -func TestInformerService(t *testing.T) { - // given - murJohn := masteruserrecord.NewMasterUserRecord(t, "johnMur") - murNoise := masteruserrecord.NewMasterUserRecord(t, "noise") - spaceJohn := space.NewSpace(test.HostOperatorNs, "johnSpace") - spaceNoise := space.NewSpace(test.HostOperatorNs, "noiseSpace") - pluginTekton := &toolchainv1alpha1.ProxyPlugin{ObjectMeta: metav1.ObjectMeta{ - Name: "tekton-results", - Namespace: test.HostOperatorNs, - }} - pluginNoise := &toolchainv1alpha1.ProxyPlugin{ObjectMeta: metav1.ObjectMeta{ - Name: "noise", - Namespace: test.HostOperatorNs, - }} - status := &toolchainv1alpha1.ToolchainStatus{ - ObjectMeta: metav1.ObjectMeta{ - Name: "toolchain-status", - Namespace: test.HostOperatorNs, - }, - Status: toolchainv1alpha1.ToolchainStatusStatus{ - HostOperator: &toolchainv1alpha1.HostOperatorStatus{ - Version: "v1alpha1", - }, - }, - } - signupJohn := usersignup.NewUserSignup(usersignup.WithName("johnUserSignup"), - usersignup.WithTargetCluster("member2")) - signupJohn.Spec.IdentityClaims = toolchainv1alpha1.IdentityClaimsEmbedded{ - PropagatedClaims: toolchainv1alpha1.PropagatedClaims{ - Sub: "foo", - OriginalSub: "sub-key", - }, - PreferredUsername: "foo@redhat.com", - GivenName: "Foo", - FamilyName: "Bar", - Company: "Red Hat", - } - signupNoise := usersignup.NewUserSignup(usersignup.WithName("noise")) - bannedAlice := &toolchainv1alpha1.BannedUser{ - ObjectMeta: metav1.ObjectMeta{ - Name: "alice", - Namespace: test.HostOperatorNs, - Labels: map[string]string{ - toolchainv1alpha1.BannedUserEmailHashLabelKey: hash.EncodeString("alice@redhat.com"), - }, - }, - Spec: toolchainv1alpha1.BannedUserSpec{ - Email: "alice@redhat.com", - }, - } - bannedBob := &toolchainv1alpha1.BannedUser{ - ObjectMeta: metav1.ObjectMeta{ - Name: "bob", - Namespace: test.HostOperatorNs, - Labels: map[string]string{ - toolchainv1alpha1.BannedUserEmailHashLabelKey: hash.EncodeString("bob@redhat.com"), - }, - }, - Spec: toolchainv1alpha1.BannedUserSpec{ - Email: "bob@redhat.com", - }, - } - bannedBobDup := &toolchainv1alpha1.BannedUser{ - ObjectMeta: metav1.ObjectMeta{ - Name: "bob-dup", - Namespace: test.HostOperatorNs, - Labels: map[string]string{ - toolchainv1alpha1.BannedUserEmailHashLabelKey: hash.EncodeString("bob@redhat.com"), - }, - }, - Spec: toolchainv1alpha1.BannedUserSpec{ - Email: "bob@redhat.com", - }, - } - - client := test.NewFakeClient(t, murJohn, murNoise, spaceJohn, spaceNoise, pluginTekton, - pluginNoise, status, signupJohn, signupNoise, bannedAlice, bannedBob, bannedBobDup) - svc := service.NewInformerService(client, test.HostOperatorNs) - - t.Run("masteruserrecords", func(t *testing.T) { - t.Run("not found", func(t *testing.T) { - // when - val, err := svc.GetMasterUserRecord("unknown") - - //then - assert.Empty(t, val) - assert.EqualError(t, err, "masteruserrecords.toolchain.dev.openshift.com \"unknown\" not found") - }) - - t.Run("found", func(t *testing.T) { - // when - val, err := svc.GetMasterUserRecord("johnMur") - - // then - require.NotNil(t, val) - require.NoError(t, err) - assert.Equal(t, murJohn.Spec, val.Spec) - }) - }) - - t.Run("spaces", func(t *testing.T) { - t.Run("not found", func(t *testing.T) { - // when - val, err := svc.GetSpace("unknown") - - // then - assert.Empty(t, val) - assert.EqualError(t, err, "spaces.toolchain.dev.openshift.com \"unknown\" not found") - }) - - t.Run("found", func(t *testing.T) { - // when - val, err := svc.GetSpace("johnSpace") - - // then - require.NotNil(t, val) - require.NoError(t, err) - assert.Equal(t, spaceJohn.Spec, val.Spec) - }) - }) - - t.Run("bannedusers", func(t *testing.T) { - t.Run("not found", func(t *testing.T) { - // when - rbb, err := svc.ListBannedUsersByEmail("unknown@unknown.com") - - // then - require.NoError(t, err) - require.Empty(t, rbb) - }) - - t.Run("invalid email", func(t *testing.T) { - // when - rbb, err := svc.ListBannedUsersByEmail("not-an-email") - - // then - require.NoError(t, err) - require.Empty(t, rbb) - }) - - t.Run("found one", func(t *testing.T) { - // when - rbb, err := svc.ListBannedUsersByEmail(bannedAlice.Spec.Email) - - // then - require.NotNil(t, rbb) - require.NoError(t, err) - require.Len(t, rbb, 1, "expected 1 result for email %s", bannedAlice.Spec.Email) - require.Equal(t, *bannedAlice, rbb[0]) - }) - - t.Run("found multiple", func(t *testing.T) { - // when - rbb, err := svc.ListBannedUsersByEmail(bannedBob.Spec.Email) - - // then - require.NotNil(t, rbb) - require.NoError(t, err) - require.Len(t, rbb, 2, "expected 2 results for email %s", bannedBob.Spec.Email) - require.ElementsMatch(t, []toolchainv1alpha1.BannedUser{*bannedBob, *bannedBobDup}, rbb) - }) - }) -} diff --git a/pkg/middleware/jwt_middleware_test.go b/pkg/middleware/jwt_middleware_test.go index 98d6262c..780d3aa3 100644 --- a/pkg/middleware/jwt_middleware_test.go +++ b/pkg/middleware/jwt_middleware_test.go @@ -10,11 +10,13 @@ import ( "github.com/codeready-toolchain/registration-service/pkg/configuration" "github.com/codeready-toolchain/registration-service/pkg/middleware" + "github.com/codeready-toolchain/registration-service/pkg/namespaced" "github.com/codeready-toolchain/registration-service/pkg/proxy" "github.com/codeready-toolchain/registration-service/pkg/server" "github.com/codeready-toolchain/registration-service/test" "github.com/codeready-toolchain/registration-service/test/fake" "github.com/codeready-toolchain/toolchain-common/pkg/status" + commontest "github.com/codeready-toolchain/toolchain-common/pkg/test" authsupport "github.com/codeready-toolchain/toolchain-common/pkg/test/auth" testconfig "github.com/codeready-toolchain/toolchain-common/pkg/test/config" @@ -86,7 +88,8 @@ func (s *TestAuthMiddlewareSuite) TestAuthMiddlewareService() { assert.Equal(s.T(), keysEndpointURL, cfg.Auth().AuthClientPublicKeysURL(), "key url not set correctly") // Setting up the routes. - err = srv.SetupRoutes(proxy.DefaultPort, prometheus.NewRegistry()) + nsClient := namespaced.NewClient(commontest.NewFakeClient(s.T()), commontest.HostOperatorNs) + err = srv.SetupRoutes(proxy.DefaultPort, prometheus.NewRegistry(), nsClient) require.NoError(s.T(), err) // Check that there are routes registered. diff --git a/pkg/middleware/promhttp_middleware_test.go b/pkg/middleware/promhttp_middleware_test.go index fd716caa..45c3c4e8 100644 --- a/pkg/middleware/promhttp_middleware_test.go +++ b/pkg/middleware/promhttp_middleware_test.go @@ -7,10 +7,12 @@ import ( "testing" "github.com/codeready-toolchain/registration-service/pkg/configuration" + "github.com/codeready-toolchain/registration-service/pkg/namespaced" "github.com/codeready-toolchain/registration-service/pkg/proxy" "github.com/codeready-toolchain/registration-service/pkg/server" "github.com/codeready-toolchain/registration-service/test" "github.com/codeready-toolchain/registration-service/test/fake" + commontest "github.com/codeready-toolchain/toolchain-common/pkg/test" authsupport "github.com/codeready-toolchain/toolchain-common/pkg/test/auth" testconfig "github.com/codeready-toolchain/toolchain-common/pkg/test/config" @@ -42,7 +44,8 @@ func (s *PromHTTPMiddlewareSuite) TestPromHTTPMiddleware() { cfg := configuration.GetRegistrationServiceConfig() assert.Equal(s.T(), keysEndpointURL, cfg.Auth().AuthClientPublicKeysURL(), "key url not set correctly") reg := prometheus.NewRegistry() - err := srv.SetupRoutes(proxy.DefaultPort, reg) + nsClient := namespaced.NewClient(commontest.NewFakeClient(s.T()), commontest.HostOperatorNs) + err := srv.SetupRoutes(proxy.DefaultPort, reg, nsClient) require.NoError(s.T(), err) // making a call on an HTTP endpoint diff --git a/pkg/proxy/handlers/spacelister.go b/pkg/proxy/handlers/spacelister.go index b2b182d2..51779c37 100644 --- a/pkg/proxy/handlers/spacelister.go +++ b/pkg/proxy/handlers/spacelister.go @@ -5,8 +5,8 @@ import ( toolchainv1alpha1 "github.com/codeready-toolchain/api/api/v1alpha1" "github.com/codeready-toolchain/registration-service/pkg/application" - "github.com/codeready-toolchain/registration-service/pkg/application/service" "github.com/codeready-toolchain/registration-service/pkg/context" + "github.com/codeready-toolchain/registration-service/pkg/namespaced" "github.com/codeready-toolchain/registration-service/pkg/proxy/metrics" "github.com/codeready-toolchain/registration-service/pkg/signup" commonproxy "github.com/codeready-toolchain/toolchain-common/pkg/proxy" @@ -27,16 +27,16 @@ const ( ) type SpaceLister struct { - GetSignupFunc func(ctx *gin.Context, userID, username string, checkUserSignupCompleted bool) (*signup.Signup, error) - GetInformerServiceFunc func() service.InformerService - ProxyMetrics *metrics.ProxyMetrics + namespaced.Client + GetSignupFunc func(ctx *gin.Context, userID, username string, checkUserSignupCompleted bool) (*signup.Signup, error) + ProxyMetrics *metrics.ProxyMetrics } -func NewSpaceLister(app application.Application, proxyMetrics *metrics.ProxyMetrics) *SpaceLister { +func NewSpaceLister(client namespaced.Client, app application.Application, proxyMetrics *metrics.ProxyMetrics) *SpaceLister { return &SpaceLister{ - GetSignupFunc: app.SignupService().GetSignupFromInformer, - GetInformerServiceFunc: app.InformerService, - ProxyMetrics: proxyMetrics, + Client: client, + GetSignupFunc: app.SignupService().GetSignupFromInformer, + ProxyMetrics: proxyMetrics, } } diff --git a/pkg/proxy/handlers/spacelister_get.go b/pkg/proxy/handlers/spacelister_get.go index 576ac5c9..8412c99a 100644 --- a/pkg/proxy/handlers/spacelister_get.go +++ b/pkg/proxy/handlers/spacelister_get.go @@ -1,6 +1,7 @@ package handlers import ( + gocontext "context" "encoding/json" "fmt" "net/http" @@ -10,6 +11,7 @@ import ( toolchainv1alpha1 "github.com/codeready-toolchain/api/api/v1alpha1" "github.com/codeready-toolchain/registration-service/pkg/context" regsercontext "github.com/codeready-toolchain/registration-service/pkg/context" + "github.com/codeready-toolchain/registration-service/pkg/namespaced" "github.com/codeready-toolchain/registration-service/pkg/proxy/metrics" "github.com/codeready-toolchain/registration-service/pkg/signup" "github.com/codeready-toolchain/toolchain-common/pkg/cluster" @@ -18,7 +20,6 @@ import ( "github.com/labstack/echo/v4" errs "github.com/pkg/errors" apierrors "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/runtime/schema" runtimeclient "sigs.k8s.io/controller-runtime/pkg/client" ) @@ -104,12 +105,7 @@ func getUserOrPublicViewerSpaceBinding(ctx echo.Context, spaceLister *SpaceListe // If more than one space bindings are found, then it returns an error. func getUserSpaceBinding(spaceLister *SpaceLister, space *toolchainv1alpha1.Space, compliantUsername string) (*toolchainv1alpha1.SpaceBinding, error) { // recursively get all the spacebindings for the current workspace - listSpaceBindingsFunc := func(spaceName string) ([]toolchainv1alpha1.SpaceBinding, error) { - spaceSelector, _ := labels.SelectorFromSet(labels.Set{toolchainv1alpha1.SpaceBindingSpaceLabelKey: spaceName}).Requirements() - murSelector, _ := labels.SelectorFromSet(labels.Set{toolchainv1alpha1.SpaceBindingMasterUserRecordLabelKey: compliantUsername}).Requirements() - return spaceLister.GetInformerServiceFunc().ListSpaceBindings(spaceSelector[0], murSelector[0]) - } - spaceBindingLister := spacebinding.NewLister(listSpaceBindingsFunc, spaceLister.GetInformerServiceFunc().GetSpace) + spaceBindingLister := NewLister(spaceLister.Client, compliantUsername) userSpaceBindings, err := spaceBindingLister.ListForSpace(space, []toolchainv1alpha1.SpaceBinding{}) if err != nil { return nil, err @@ -127,6 +123,26 @@ func getUserSpaceBinding(spaceLister *SpaceLister, space *toolchainv1alpha1.Spac return &userSpaceBindings[0], nil } +func NewLister(nsClient namespaced.Client, withMurName string) *spacebinding.Lister { + listSpaceBindingsFunc := func(spaceName string) ([]toolchainv1alpha1.SpaceBinding, error) { + labelSelector := runtimeclient.MatchingLabels{ + toolchainv1alpha1.SpaceBindingSpaceLabelKey: spaceName, + } + if withMurName != "" { + labelSelector[toolchainv1alpha1.SpaceBindingMasterUserRecordLabelKey] = withMurName + } + bindings := &toolchainv1alpha1.SpaceBindingList{} + if err := nsClient.List(gocontext.TODO(), bindings, runtimeclient.InNamespace(nsClient.Namespace), labelSelector); err != nil { + return nil, err + } + return bindings.Items, nil + } + return spacebinding.NewLister(listSpaceBindingsFunc, func(spaceName string) (*toolchainv1alpha1.Space, error) { + space := &toolchainv1alpha1.Space{} + return space, nsClient.Get(gocontext.TODO(), nsClient.NamespacedName(spaceName), space) + }) +} + // GetUserWorkspaceWithBindings returns a workspace object with the required fields+bindings (the list with all the users access details). func GetUserWorkspaceWithBindings(ctx echo.Context, spaceLister *SpaceLister, workspaceName string, GetMembersFunc cluster.GetMemberClustersFunc) (*toolchainv1alpha1.Workspace, error) { userSignup, space, err := getUserSignupAndSpace(ctx, spaceLister, workspaceName) @@ -139,11 +155,7 @@ func GetUserWorkspaceWithBindings(ctx echo.Context, spaceLister *SpaceLister, wo } // recursively get all the spacebindings for the current workspace - listSpaceBindingsFunc := func(spaceName string) ([]toolchainv1alpha1.SpaceBinding, error) { - ss, _ := labels.SelectorFromSet(labels.Set{toolchainv1alpha1.SpaceBindingSpaceLabelKey: spaceName}).Requirements() - return spaceLister.GetInformerServiceFunc().ListSpaceBindings(ss[0]) - } - spaceBindingLister := spacebinding.NewLister(listSpaceBindingsFunc, spaceLister.GetInformerServiceFunc().GetSpace) + spaceBindingLister := NewLister(spaceLister.Client, "") allSpaceBindings, err := spaceBindingLister.ListForSpace(space, []toolchainv1alpha1.SpaceBinding{}) if err != nil { ctx.Logger().Error(err, "failed to list space bindings") @@ -181,8 +193,8 @@ func GetUserWorkspaceWithBindings(ctx echo.Context, spaceLister *SpaceLister, wo } // add available roles, this field is populated only for the GET workspace request - nsTemplateTier, err := spaceLister.GetInformerServiceFunc().GetNSTemplateTier(space.Spec.TierName) - if err != nil { + nsTemplateTier := &toolchainv1alpha1.NSTemplateTier{} + if err := spaceLister.Get(ctx.Request().Context(), spaceLister.NamespacedName(space.Spec.TierName), nsTemplateTier); err != nil { ctx.Logger().Error(errs.Wrap(err, "unable to get nstemplatetier")) return nil, err } @@ -206,9 +218,8 @@ func getUserSignupAndSpace(ctx echo.Context, spaceLister *SpaceLister, workspace Name: toolchainv1alpha1.KubesawAuthenticatedUsername, } } - - space, err := spaceLister.GetInformerServiceFunc().GetSpace(workspaceName) - if err != nil { + space := &toolchainv1alpha1.Space{} + if err := spaceLister.Get(gocontext.TODO(), spaceLister.NamespacedName(workspaceName), space); err != nil { ctx.Logger().Error(errs.Wrap(err, "unable to get space")) return userSignup, nil, nil } diff --git a/pkg/proxy/handlers/spacelister_get_test.go b/pkg/proxy/handlers/spacelister_get_test.go index 762cd3e1..2643f111 100644 --- a/pkg/proxy/handlers/spacelister_get_test.go +++ b/pkg/proxy/handlers/spacelister_get_test.go @@ -10,9 +10,8 @@ import ( "time" toolchainv1alpha1 "github.com/codeready-toolchain/api/api/v1alpha1" - "github.com/codeready-toolchain/registration-service/pkg/application/service" rcontext "github.com/codeready-toolchain/registration-service/pkg/context" - infservice "github.com/codeready-toolchain/registration-service/pkg/informers/service" + "github.com/codeready-toolchain/registration-service/pkg/namespaced" "github.com/codeready-toolchain/registration-service/pkg/proxy/handlers" "github.com/codeready-toolchain/registration-service/pkg/proxy/metrics" proxytest "github.com/codeready-toolchain/registration-service/pkg/proxy/test" @@ -557,11 +556,9 @@ func testSpaceListerGet(t *testing.T, publicViewerEnabled bool) { proxyMetrics := metrics.NewProxyMetrics(prometheus.NewRegistry()) s := &handlers.SpaceLister{ + Client: namespaced.NewClient(fakeClient, test.HostOperatorNs), GetSignupFunc: signupProvider, - GetInformerServiceFunc: func() service.InformerService { - return infservice.NewInformerService(fakeClient, test.HostOperatorNs) - }, - ProxyMetrics: proxyMetrics, + ProxyMetrics: proxyMetrics, } e := echo.New() @@ -734,11 +731,9 @@ func TestGetUserWorkspace(t *testing.T) { proxyMetrics := metrics.NewProxyMetrics(prometheus.NewRegistry()) s := &handlers.SpaceLister{ + Client: namespaced.NewClient(fakeClient, test.HostOperatorNs), GetSignupFunc: signupProvider, - GetInformerServiceFunc: func() service.InformerService { - return infservice.NewInformerService(fakeClient, test.HostOperatorNs) - }, - ProxyMetrics: proxyMetrics, + ProxyMetrics: proxyMetrics, } e := echo.New() @@ -843,11 +838,9 @@ func TestSpaceListerGetPublicViewerEnabled(t *testing.T) { proxyMetrics := metrics.NewProxyMetrics(prometheus.NewRegistry()) s := &handlers.SpaceLister{ + Client: namespaced.NewClient(fakeClient, test.HostOperatorNs), GetSignupFunc: signupProvider, - GetInformerServiceFunc: func() service.InformerService { - return infservice.NewInformerService(fakeClient, test.HostOperatorNs) - }, - ProxyMetrics: proxyMetrics, + ProxyMetrics: proxyMetrics, } e := echo.New() @@ -980,11 +973,9 @@ func TestGetUserWorkspaceWithBindingsWithPublicViewerEnabled(t *testing.T) { proxyMetrics := metrics.NewProxyMetrics(prometheus.NewRegistry()) s := &handlers.SpaceLister{ + Client: namespaced.NewClient(fakeClient, test.HostOperatorNs), GetSignupFunc: signupProvider, - GetInformerServiceFunc: func() service.InformerService { - return infservice.NewInformerService(fakeClient, test.HostOperatorNs) - }, - ProxyMetrics: proxyMetrics, + ProxyMetrics: proxyMetrics, } e := echo.New() diff --git a/pkg/proxy/handlers/spacelister_list.go b/pkg/proxy/handlers/spacelister_list.go index afa51985..dfbd8498 100644 --- a/pkg/proxy/handlers/spacelister_list.go +++ b/pkg/proxy/handlers/spacelister_list.go @@ -1,6 +1,7 @@ package handlers import ( + gocontext "context" "encoding/json" "fmt" "net/http" @@ -16,6 +17,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/selection" + runtimeclient "sigs.k8s.io/controller-runtime/pkg/client" ) func HandleSpaceListRequest(spaceLister *SpaceLister) echo.HandlerFunc { @@ -90,7 +92,12 @@ func listSpaceBindingsForUsers(spaceLister *SpaceLister, murNames []string) ([]t if err != nil { return nil, err } - return spaceLister.GetInformerServiceFunc().ListSpaceBindings(*murSelector) + selector := runtimeclient.MatchingLabelsSelector{Selector: labels.NewSelector().Add(*murSelector)} + bindings := &toolchainv1alpha1.SpaceBindingList{} + if err := spaceLister.List(gocontext.TODO(), bindings, runtimeclient.InNamespace(spaceLister.Namespace), selector); err != nil { + return nil, err + } + return bindings.Items, err } func workspacesFromSpaceBindings(ctx echo.Context, spaceLister *SpaceLister, signupName string, spaceBindings []toolchainv1alpha1.SpaceBinding) []toolchainv1alpha1.Workspace { @@ -116,5 +123,6 @@ func getSpace(spaceLister *SpaceLister, spaceBinding *toolchainv1alpha1.SpaceBin // log error and continue so that the api behaves in a best effort manner return nil, fmt.Errorf("spacebinding has no '%s' label", toolchainv1alpha1.SpaceBindingSpaceLabelKey) } - return spaceLister.GetInformerServiceFunc().GetSpace(spaceName) + space := &toolchainv1alpha1.Space{} + return space, spaceLister.Get(gocontext.TODO(), spaceLister.NamespacedName(spaceName), space) } diff --git a/pkg/proxy/handlers/spacelister_list_test.go b/pkg/proxy/handlers/spacelister_list_test.go index 7ca5eff4..3aa9c73d 100644 --- a/pkg/proxy/handlers/spacelister_list_test.go +++ b/pkg/proxy/handlers/spacelister_list_test.go @@ -9,7 +9,7 @@ import ( "testing" "time" - infservice "github.com/codeready-toolchain/registration-service/pkg/informers/service" + "github.com/codeready-toolchain/registration-service/pkg/namespaced" "github.com/gin-gonic/gin" "github.com/labstack/echo/v4" "github.com/prometheus/client_golang/prometheus" @@ -19,7 +19,6 @@ import ( runtimeclient "sigs.k8s.io/controller-runtime/pkg/client" toolchainv1alpha1 "github.com/codeready-toolchain/api/api/v1alpha1" - "github.com/codeready-toolchain/registration-service/pkg/application/service" rcontext "github.com/codeready-toolchain/registration-service/pkg/context" "github.com/codeready-toolchain/registration-service/pkg/proxy/handlers" "github.com/codeready-toolchain/registration-service/pkg/proxy/metrics" @@ -77,11 +76,9 @@ func TestListUserWorkspaces(t *testing.T) { proxyMetrics := metrics.NewProxyMetrics(prometheus.NewRegistry()) s := &handlers.SpaceLister{ + Client: namespaced.NewClient(fakeClient, test.HostOperatorNs), GetSignupFunc: signupProvider, - GetInformerServiceFunc: func() service.InformerService { - return infservice.NewInformerService(fakeClient, test.HostOperatorNs) - }, - ProxyMetrics: proxyMetrics, + ProxyMetrics: proxyMetrics, } e := echo.New() @@ -207,11 +204,9 @@ func TestHandleSpaceListRequest(t *testing.T) { proxyMetrics := metrics.NewProxyMetrics(prometheus.NewRegistry()) s := &handlers.SpaceLister{ + Client: namespaced.NewClient(fakeClient, test.HostOperatorNs), GetSignupFunc: signupProvider, - GetInformerServiceFunc: func() service.InformerService { - return infservice.NewInformerService(fakeClient, test.HostOperatorNs) - }, - ProxyMetrics: proxyMetrics, + ProxyMetrics: proxyMetrics, } e := echo.New() diff --git a/pkg/proxy/proxy.go b/pkg/proxy/proxy.go index e9425456..b76ed983 100644 --- a/pkg/proxy/proxy.go +++ b/pkg/proxy/proxy.go @@ -23,16 +23,19 @@ import ( "github.com/codeready-toolchain/registration-service/pkg/context" crterrors "github.com/codeready-toolchain/registration-service/pkg/errors" "github.com/codeready-toolchain/registration-service/pkg/log" + "github.com/codeready-toolchain/registration-service/pkg/namespaced" "github.com/codeready-toolchain/registration-service/pkg/proxy/access" "github.com/codeready-toolchain/registration-service/pkg/proxy/handlers" "github.com/codeready-toolchain/registration-service/pkg/proxy/metrics" "github.com/codeready-toolchain/registration-service/pkg/signup" commoncluster "github.com/codeready-toolchain/toolchain-common/pkg/cluster" + "github.com/codeready-toolchain/toolchain-common/pkg/hash" "github.com/labstack/echo/v4" "github.com/labstack/echo/v4/middleware" glog "github.com/labstack/gommon/log" errs "github.com/pkg/errors" "k8s.io/apimachinery/pkg/util/httpstream" + "sigs.k8s.io/controller-runtime/pkg/client" "k8s.io/apiserver/pkg/util/wsstream" ) @@ -60,6 +63,7 @@ func authorizationEndpointTarget() string { } type Proxy struct { + namespaced.Client app application.Application tokenParser *auth.TokenParser spaceLister *handlers.SpaceLister @@ -67,15 +71,16 @@ type Proxy struct { getMembersFunc commoncluster.GetMemberClustersFunc } -func NewProxy(app application.Application, proxyMetrics *metrics.ProxyMetrics, getMembersFunc commoncluster.GetMemberClustersFunc) (*Proxy, error) { +func NewProxy(nsClient namespaced.Client, app application.Application, proxyMetrics *metrics.ProxyMetrics, getMembersFunc commoncluster.GetMemberClustersFunc) (*Proxy, error) { tokenParser, err := auth.DefaultTokenParser() if err != nil { return nil, err } // init handlers - spaceLister := handlers.NewSpaceLister(app, proxyMetrics) + spaceLister := handlers.NewSpaceLister(nsClient, app, proxyMetrics) return &Proxy{ + Client: nsClient, app: app, tokenParser: tokenParser, spaceLister: spaceLister, @@ -352,7 +357,8 @@ func (p *Proxy) checkUserIsProvisionedAndSpaceExists(ctx echo.Context, userID, u // checkSpaceExists checks whether the Space exists. func (p *Proxy) checkSpaceExists(workspaceName string) error { - if _, err := p.app.InformerService().GetSpace(workspaceName); err != nil { + space := &toolchainv1alpha1.Space{} + if err := p.Get(gocontext.TODO(), p.NamespacedName(workspaceName), space); err != nil { // log the actual error but do not return it so that it doesn't reveal information about a space that may not belong to the requestor log.Errorf(nil, err, "requested space '%s' does not exist", workspaceName) return fmt.Errorf("access to workspace '%s' is forbidden", workspaceName) @@ -590,14 +596,16 @@ func (p *Proxy) ensureUserIsNotBanned() echo.MiddlewareFunc { } // retrieve banned users - uu, err := p.app.InformerService().ListBannedUsersByEmail(email) - if err != nil { + hashedEmail := hash.EncodeString(email) + bannedUsers := &toolchainv1alpha1.BannedUserList{} + if err := p.List(ctx.Request().Context(), bannedUsers, client.InNamespace(p.Namespace), + client.MatchingLabels{toolchainv1alpha1.BannedUserEmailHashLabelKey: hashedEmail}); err != nil { ctx.Logger().Errorf("error retrieving the list of banned users with email address %s: %v", email, err) return crterrors.NewInternalError(errs.New("user access could not be verified"), "could not define user access") } // if a matching Banned user is found, then user is banned - if len(uu) > 0 { + if len(bannedUsers.Items) > 0 { return crterrors.NewForbiddenError("user access is forbidden", "user access is forbidden") } diff --git a/pkg/proxy/proxy_community_test.go b/pkg/proxy/proxy_community_test.go index 3e59b324..67134e98 100644 --- a/pkg/proxy/proxy_community_test.go +++ b/pkg/proxy/proxy_community_test.go @@ -6,10 +6,7 @@ import ( "net/http/httptest" "time" - appservice "github.com/codeready-toolchain/registration-service/pkg/application/service" "github.com/codeready-toolchain/registration-service/pkg/auth" - infservice "github.com/codeready-toolchain/registration-service/pkg/informers/service" - "github.com/codeready-toolchain/registration-service/pkg/namespaced" "github.com/codeready-toolchain/registration-service/pkg/proxy/handlers" "github.com/codeready-toolchain/registration-service/pkg/signup" "github.com/codeready-toolchain/registration-service/test/fake" @@ -144,23 +141,20 @@ func (s *TestProxySuite) checkProxyCommunityOK(fakeApp *fake.ProxyFakeApp, p *Pr ) // configure informer - inf := infservice.NewInformerService(cli, commontest.HostOperatorNs) - nsClient := namespaced.NewClient(cli, commontest.HostOperatorNs) + p.Client.Client = cli // configure Application fakeApp.Err = nil - fakeApp.InformerServiceMock = inf - fakeApp.MemberClusterServiceMock = s.newMemberClusterServiceWithMembers(nsClient, signupService, testServer.URL) + fakeApp.MemberClusterServiceMock = s.newMemberClusterServiceWithMembers(p.Client, signupService, testServer.URL) fakeApp.SignupServiceMock = signupService s.Application.MockSignupService(signupService) - s.Application.MockInformerService(inf) // configure proxy p.spaceLister = &handlers.SpaceLister{ - GetSignupFunc: fakeApp.SignupServiceMock.GetSignupFromInformer, - GetInformerServiceFunc: func() appservice.InformerService { return inf }, - ProxyMetrics: p.metrics, + Client: p.Client, + GetSignupFunc: fakeApp.SignupServiceMock.GetSignupFromInformer, + ProxyMetrics: p.metrics, } // run test cases diff --git a/pkg/proxy/proxy_test.go b/pkg/proxy/proxy_test.go index f803789b..5e8fd5e2 100644 --- a/pkg/proxy/proxy_test.go +++ b/pkg/proxy/proxy_test.go @@ -19,7 +19,6 @@ import ( appservice "github.com/codeready-toolchain/registration-service/pkg/application/service" "github.com/codeready-toolchain/registration-service/pkg/auth" - infservice "github.com/codeready-toolchain/registration-service/pkg/informers/service" "github.com/codeready-toolchain/registration-service/pkg/namespaced" "github.com/codeready-toolchain/registration-service/pkg/proxy/access" "github.com/codeready-toolchain/registration-service/pkg/proxy/handlers" @@ -104,13 +103,11 @@ func (s *TestProxySuite) TestProxy() { } return fakeClient.Client.List(ctx, list, opts...) } - inf := infservice.NewInformerService(fakeClient, commontest.HostOperatorNs) + nsClient := namespaced.NewClient(fakeClient, commontest.HostOperatorNs) - fakeApp := &fake.ProxyFakeApp{ - InformerServiceMock: inf, - } + fakeApp := &fake.ProxyFakeApp{} proxyMetrics := metrics.NewProxyMetrics(prometheus.NewRegistry()) - p, err := NewProxy(fakeApp, proxyMetrics, proxytest.NewGetMembersFunc(commontest.NewFakeClient(s.T()))) + p, err := NewProxy(nsClient, fakeApp, proxyMetrics, proxytest.NewGetMembersFunc(commontest.NewFakeClient(s.T()))) require.NoError(s.T(), err) server := p.StartProxy(DefaultPort) @@ -136,7 +133,7 @@ func (s *TestProxySuite) TestProxy() { func (s *TestProxySuite) spinUpProxy(fakeApp *fake.ProxyFakeApp, port string) (*Proxy, *http.Server) { proxyMetrics := metrics.NewProxyMetrics(prometheus.NewRegistry()) - p, err := NewProxy( + p, err := NewProxy(namespaced.NewClient(commontest.NewFakeClient(s.T()), commontest.HostOperatorNs), fakeApp, proxyMetrics, proxytest.NewGetMembersFunc(commontest.NewFakeClient(s.T()))) require.NoError(s.T(), err) @@ -850,19 +847,13 @@ func (s *TestProxySuite) checkProxyOK(fakeApp *fake.ProxyFakeApp, p *Proxy) { fake.NewSpaceBinding("mycoolworkspace-smith2", "smith2", "mycoolworkspace", "admin"), proxyPlugin, fake.NewBase1NSTemplateTier()) - inf := infservice.NewInformerService(fakeClient, commontest.HostOperatorNs) - nsClient := namespaced.NewClient(fakeClient, commontest.HostOperatorNs) - - s.Application.MockInformerService(inf) - fakeApp.MemberClusterServiceMock = s.newMemberClusterServiceWithMembers(nsClient, fakeApp.SignupServiceMock, testServer.URL) - fakeApp.InformerServiceMock = inf + p.Client.Client = fakeClient + fakeApp.MemberClusterServiceMock = s.newMemberClusterServiceWithMembers(p.Client, fakeApp.SignupServiceMock, testServer.URL) p.spaceLister = &handlers.SpaceLister{ + Client: p.Client, GetSignupFunc: fakeApp.SignupServiceMock.GetSignupFromInformer, - GetInformerServiceFunc: func() appservice.InformerService { - return inf - }, - ProxyMetrics: p.metrics, + ProxyMetrics: p.metrics, } if tc.OverrideGetSignupFunc != nil { p.spaceLister.GetSignupFunc = tc.OverrideGetSignupFunc diff --git a/pkg/proxy/service/cluster_service_test.go b/pkg/proxy/service/cluster_service_test.go index 00fad999..4e05e5d0 100644 --- a/pkg/proxy/service/cluster_service_test.go +++ b/pkg/proxy/service/cluster_service_test.go @@ -7,7 +7,6 @@ import ( "net/url" "testing" - infservice "github.com/codeready-toolchain/registration-service/pkg/informers/service" "github.com/codeready-toolchain/registration-service/pkg/namespaced" "github.com/codeready-toolchain/registration-service/pkg/proxy/access" "github.com/codeready-toolchain/registration-service/pkg/proxy/service" @@ -157,6 +156,7 @@ func (s *TestClusterServiceSuite) TestGetClusterAccess() { s.Run("unable to get space", func() { s.Run("informer service returns error", func() { + fakeClient := commontest.NewFakeClient(s.T()) fakeClient.MockGet = func(ctx context.Context, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error { if _, ok := obj.(*toolchainv1alpha1.Space); ok && key.Name == "smith2" { return fmt.Errorf("oopsi woopsi") @@ -166,8 +166,8 @@ func (s *TestClusterServiceSuite) TestGetClusterAccess() { defer func() { fakeClient.MockGet = nil }() - inf := infservice.NewInformerService(fakeClient, commontest.HostOperatorNs) - s.Application.MockInformerService(inf) + nsClient := namespaced.NewClient(fakeClient, commontest.HostOperatorNs) + svc := service.NewMemberClusterService(nsClient, sc) // when _, err := svc.GetClusterAccess("789-ready", "", "smith2", "", publicViewerEnabled) diff --git a/pkg/server/in_cluster_application.go b/pkg/server/in_cluster_application.go index 60ba20c8..9658050d 100644 --- a/pkg/server/in_cluster_application.go +++ b/pkg/server/in_cluster_application.go @@ -5,18 +5,17 @@ import ( "github.com/codeready-toolchain/registration-service/pkg/application/service" "github.com/codeready-toolchain/registration-service/pkg/application/service/factory" "github.com/codeready-toolchain/registration-service/pkg/namespaced" - "sigs.k8s.io/controller-runtime/pkg/client" ) // NewInClusterApplication creates a new in-cluster application with the specified configuration and options. This // application type is intended to run inside a Kubernetes cluster, where it makes use of the rest.InClusterConfig() // function to determine which Kubernetes configuration to use to create the REST client that interacts with the // Kubernetes service endpoints. -func NewInClusterApplication(client client.Client, namespace string, options ...factory.Option) application.Application { +func NewInClusterApplication(client namespaced.Client, options ...factory.Option) application.Application { return &InClusterApplication{ serviceFactory: factory.NewServiceFactory(append(options, factory.WithServiceContextOptions( - factory.NamespacedClientOption(namespaced.NewClient(client, namespace))))...), + factory.NamespacedClientOption(client)))...), } } @@ -24,10 +23,6 @@ type InClusterApplication struct { serviceFactory *factory.ServiceFactory } -func (r InClusterApplication) InformerService() service.InformerService { - return r.serviceFactory.InformerService() -} - func (r InClusterApplication) SignupService() service.SignupService { return r.serviceFactory.SignupService() } diff --git a/pkg/server/routes.go b/pkg/server/routes.go index b8000926..1882e48f 100644 --- a/pkg/server/routes.go +++ b/pkg/server/routes.go @@ -6,6 +6,7 @@ import ( "github.com/codeready-toolchain/registration-service/pkg/configuration" "github.com/codeready-toolchain/registration-service/pkg/controller" "github.com/codeready-toolchain/registration-service/pkg/middleware" + "github.com/codeready-toolchain/registration-service/pkg/namespaced" "github.com/gin-contrib/static" errs "github.com/pkg/errors" @@ -14,7 +15,7 @@ import ( // SetupRoutes registers handlers for various URL paths. // proxyPort is the API Proxy Server port to be used to setup a route for the health checker for the proxy. -func (srv *RegistrationServer) SetupRoutes(proxyPort string, reg *prometheus.Registry) error { +func (srv *RegistrationServer) SetupRoutes(proxyPort string, reg *prometheus.Registry, nsClient namespaced.Client) error { var err error _, err = auth.InitializeDefaultTokenParser() if err != nil { @@ -53,7 +54,7 @@ func (srv *RegistrationServer) SetupRoutes(proxyPort string, reg *prometheus.Reg authConfigCtrl := controller.NewAuthConfig() analyticsCtrl := controller.NewAnalytics() signupCtrl := controller.NewSignup(srv.application) - usernamesCtrl := controller.NewUsernames(srv.application) + usernamesCtrl := controller.NewUsernames(nsClient) // unsecured routes unsecuredV1 := srv.router.Group("/api/v1") diff --git a/pkg/server/server_test.go b/pkg/server/server_test.go index dc12f33a..fc37e81c 100644 --- a/pkg/server/server_test.go +++ b/pkg/server/server_test.go @@ -6,9 +6,11 @@ import ( "testing" "time" + "github.com/codeready-toolchain/registration-service/pkg/namespaced" "github.com/codeready-toolchain/registration-service/pkg/server" "github.com/codeready-toolchain/registration-service/test" "github.com/codeready-toolchain/registration-service/test/fake" + commontest "github.com/codeready-toolchain/toolchain-common/pkg/test" "github.com/prometheus/client_golang/prometheus" "github.com/stretchr/testify/assert" @@ -38,7 +40,8 @@ func (s *TestServerSuite) TestServer() { fake.MockKeycloakCertsCall(s.T()) // Setting up the routes. - err := srv.SetupRoutes("8091", prometheus.NewRegistry()) // uses a different proxy port than the default one to avoid collision with other concurrent tests + nsClient := namespaced.NewClient(commontest.NewFakeClient(s.T()), commontest.HostOperatorNs) + err := srv.SetupRoutes("8091", prometheus.NewRegistry(), nsClient) // uses a different proxy port than the default one to avoid collision with other concurrent tests require.NoError(s.T(), err) gock.OffAll() diff --git a/test/fake/mockable_application.go b/test/fake/mockable_application.go index 8fed8c2d..c3416b94 100644 --- a/test/fake/mockable_application.go +++ b/test/fake/mockable_application.go @@ -13,7 +13,6 @@ func NewMockableApplication(options ...factory.Option) *MockableApplication { type MockableApplication struct { serviceFactory *factory.ServiceFactory - mockInformerService service.InformerService mockSignupService service.SignupService mockVerificationService service.VerificationService } @@ -39,14 +38,3 @@ func (m *MockableApplication) VerificationService() service.VerificationService func (m *MockableApplication) MemberClusterService() service.MemberClusterService { return m.serviceFactory.MemberClusterService() } - -func (m *MockableApplication) InformerService() service.InformerService { - if m.mockInformerService != nil { - return m.mockInformerService - } - return m.serviceFactory.InformerService() -} - -func (m *MockableApplication) MockInformerService(svc service.InformerService) { - m.mockInformerService = svc -} diff --git a/test/fake/proxy.go b/test/fake/proxy.go index 92133d28..952a29d4 100644 --- a/test/fake/proxy.go +++ b/test/fake/proxy.go @@ -15,14 +15,6 @@ type ProxyFakeApp struct { Err error SignupServiceMock service.SignupService MemberClusterServiceMock service.MemberClusterService - InformerServiceMock service.InformerService -} - -func (a *ProxyFakeApp) InformerService() service.InformerService { - if a.InformerServiceMock != nil { - return a.InformerServiceMock - } - panic("InformerService shouldn't be called") } func (a *ProxyFakeApp) SignupService() service.SignupService { diff --git a/test/util/application.go b/test/util/application.go index 54cfed82..0943eb77 100644 --- a/test/util/application.go +++ b/test/util/application.go @@ -5,6 +5,7 @@ import ( "github.com/codeready-toolchain/registration-service/pkg/application" "github.com/codeready-toolchain/registration-service/pkg/application/service/factory" + "github.com/codeready-toolchain/registration-service/pkg/namespaced" "github.com/codeready-toolchain/registration-service/pkg/server" commontest "github.com/codeready-toolchain/toolchain-common/pkg/test" "k8s.io/apimachinery/pkg/runtime" @@ -17,6 +18,6 @@ func PrepareInClusterApp(t *testing.T, objects ...runtime.Object) (*commontest.F func PrepareInClusterAppWithOption(t *testing.T, option factory.Option, objects ...runtime.Object) (*commontest.FakeClient, application.Application) { fakeClient := commontest.NewFakeClient(t, objects...) - app := server.NewInClusterApplication(fakeClient, commontest.HostOperatorNs, option) + app := server.NewInClusterApplication(namespaced.NewClient(fakeClient, commontest.HostOperatorNs), option) return fakeClient, app }