Skip to content

Commit

Permalink
authorization for UpdateUserAddons
Browse files Browse the repository at this point in the history
  • Loading branch information
jlandowner committed Aug 2, 2023
1 parent 205b8fc commit bf76964
Showing 1 changed file with 31 additions and 3 deletions.
34 changes: 31 additions & 3 deletions internal/dashboard/user_sub_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,50 @@ package dashboard

import (
"context"
"fmt"
"reflect"

connect_go "github.com/bufbuild/connect-go"
"k8s.io/apimachinery/pkg/types"

"github.com/cosmo-workspace/cosmo/pkg/clog"
"github.com/cosmo-workspace/cosmo/pkg/kosmo"
"github.com/cosmo-workspace/cosmo/pkg/useraddon"
dashv1alpha1 "github.com/cosmo-workspace/cosmo/proto/gen/dashboard/v1alpha1"
)

func (s *Server) UpdateUserAddons(ctx context.Context, req *connect_go.Request[dashv1alpha1.UpdateUserAddonsRequest]) (*connect_go.Response[dashv1alpha1.UpdateUserAddonsResponse], error) {
log := clog.FromContext(ctx).WithCaller()
log.Debug().Info("request", "req", req)

currentUser, err := s.Klient.GetUser(ctx, req.Msg.UserName)
if err != nil {
return nil, ErrResponse(log, err)
}

// caller can attach or detach only:
// - User who have group-role which caller is admin for
// - Addons which is allowed for caller to manage
err = adminAuthentication(ctx,
validateCallerHasAdminForAtLeastOneRole(currentUser.Spec.Roles))
if err != nil {
return nil, ErrResponse(log, err)
}

caller := callerFromContext(ctx)
if caller == nil {
return nil, kosmo.NewInternalServerError("unable get caller", nil)
}
for _, addon := range diff(currentUser.Spec.Addons, convertDashv1alpha1UserAddonToUserAddon(req.Msg.Addons)) {
tmpl := useraddon.EmptyTemplateObject(addon)
err := s.Klient.Get(ctx, types.NamespacedName{Name: tmpl.GetName()}, tmpl)
if err != nil {
return nil, kosmo.NewInternalServerError(fmt.Sprintf("failed to fetch addon '%s'", tmpl.GetName()), nil)
}
if ok := kosmo.IsAllowedToUseTemplate(ctx, caller, tmpl); !ok {
return nil, kosmo.NewForbiddenError("no roles for addon", nil)
}
}

addons := convertDashv1alpha1UserAddonToUserAddon(req.Msg.Addons)
user, err := s.Klient.UpdateUser(ctx, req.Msg.UserName, kosmo.UpdateUserOpts{
Expand Down Expand Up @@ -56,15 +84,15 @@ func (s *Server) UpdateUserDisplayName(ctx context.Context, req *connect_go.Requ
return connect_go.NewResponse(res), nil
}

func diff(slice1 []string, slice2 []string) []string {
var diff []string
func diff[T any](slice1 []T, slice2 []T) []T {
var diff []T
// Loop two times, first to find slice1 strings not in slice2,
// second loop to find slice2 strings not in slice1
for i := 0; i < 2; i++ {
for _, s1 := range slice1 {
found := false
for _, s2 := range slice2 {
if s1 == s2 {
if reflect.DeepEqual(s1, s2) {
found = true
break
}
Expand Down

0 comments on commit bf76964

Please sign in to comment.