diff --git a/changelog/unreleased/add-user-type-upgrade-downgrade.md b/changelog/unreleased/add-user-type-upgrade-downgrade.md new file mode 100644 index 00000000000..9ce0f1085a4 --- /dev/null +++ b/changelog/unreleased/add-user-type-upgrade-downgrade.md @@ -0,0 +1,5 @@ +Enhancement: Added user type upgrade/downgrade + +Added the mechanism to disable/enable personal spaces on user type upgrade/downgrade + +https://github.com/owncloud/ocis/pull/11678 diff --git a/ocis-pkg/shared/storage_utils.go b/ocis-pkg/shared/storage_utils.go new file mode 100644 index 00000000000..6ca4106e04a --- /dev/null +++ b/ocis-pkg/shared/storage_utils.go @@ -0,0 +1,145 @@ +package shared + +import ( + "context" + "errors" + "fmt" + + gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1" + userv1beta1 "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" + cs3rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1" + storageprovider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" + libregraph "github.com/owncloud/libre-graph-api-go" + "github.com/owncloud/ocis/v2/services/graph/pkg/errorcode" + "github.com/owncloud/reva/v2/pkg/appctx" + "github.com/owncloud/reva/v2/pkg/utils" +) + +const ( + _spaceTypePersonal = "personal" + _spaceStateTrashed = "trashed" +) + +var ( + // ErrNotFound is returned when a personal space not found. + ErrNotFound = errors.New("personal space not found") +) + +// DisablePersonalSpace disables (deletes) the personal storage space for the given userID. +// If the personal space is already deleted (trashed), it is a no-op. +// Returns an error if the space cannot be found or the deletion fails. +func DisablePersonalSpace(ctx context.Context, client gateway.GatewayAPIClient, userID string) error { + logger := appctx.GetLogger(ctx) + sp, err := getPersonalSpace(ctx, client, userID) + if err != nil { + return fmt.Errorf("failed to retrieve personal space: %w", err) + } + if isTrashed(sp) { + logger.Debug().Str("userID", userID).Msg("the personal space already deleted") + return nil + } + + dRes, derr := client.DeleteStorageSpace(ctx, &storageprovider.DeleteStorageSpaceRequest{ + Id: &storageprovider.StorageSpaceId{OpaqueId: sp.GetId().GetOpaqueId()}, + }) + if derr != nil { + return fmt.Errorf("failed to disable personal space: %w", derr) + } + if dRes.GetStatus().GetCode() != cs3rpc.Code_CODE_OK { + return errorcode.NewFromStatusCode(dRes.GetStatus().GetCode(), dRes.GetStatus().GetMessage()) + } + return nil +} + +// EnsurePersonalSpace ensures that a personal storage space exists and is enabled for the given user. +// If the personal space is found and is trashed, it restores it. +// If the personal space does not exist, it creates a new one. +// Returns an error if the operation fails. +func EnsurePersonalSpace(ctx context.Context, client gateway.GatewayAPIClient, user libregraph.User) error { + sp, err := getPersonalSpace(ctx, client, user.GetId()) + if err != nil && !errors.Is(err, ErrNotFound) { + return err + } + + if sp != nil && isTrashed(sp) { + req := &storageprovider.UpdateStorageSpaceRequest{ + Opaque: utils.AppendPlainToOpaque(nil, "restore", "true"), + StorageSpace: &storageprovider.StorageSpace{ + Id: &storageprovider.StorageSpaceId{OpaqueId: sp.GetId().GetOpaqueId()}, + Root: sp.GetRoot(), + }, + } + uRes, uerr := client.UpdateStorageSpace(ctx, req) + if uerr != nil { + return fmt.Errorf("failed to enable personal space: %w", uerr) + } + if uRes.GetStatus().GetCode() != cs3rpc.Code_CODE_OK { + return errorcode.NewFromStatusCode(uRes.GetStatus().GetCode(), uRes.GetStatus().GetMessage()) + } + return nil + } + if errors.Is(err, ErrNotFound) { + req := &storageprovider.CreateStorageSpaceRequest{ + Type: _spaceTypePersonal, + Owner: &userv1beta1.User{Id: &userv1beta1.UserId{OpaqueId: user.GetId()}}, + Name: user.GetDisplayName(), + } + cRes, cerr := client.CreateStorageSpace(ctx, req) + if cerr != nil { + return fmt.Errorf("failed to create personal space: %w", cerr) + } + if cRes.GetStatus().GetCode() == cs3rpc.Code_CODE_ALREADY_EXISTS { + return nil + } + if cRes.GetStatus().GetCode() != cs3rpc.Code_CODE_OK { + return errorcode.NewFromStatusCode(cRes.GetStatus().GetCode(), cRes.GetStatus().GetMessage()) + } + } + return nil +} + +func getPersonalSpace(ctx context.Context, client gateway.GatewayAPIClient, userID string) (*storageprovider.StorageSpace, error) { + lspr, err := client.ListStorageSpaces(ctx, &storageprovider.ListStorageSpacesRequest{ + Opaque: utils.AppendPlainToOpaque(nil, "unrestricted", "T"), + Filters: []*storageprovider.ListStorageSpacesRequest_Filter{ + listStorageSpacesUserFilter(userID), + listStorageSpacesTypeFilter(_spaceTypePersonal)}, + }) + if err != nil { + return nil, fmt.Errorf("failed to retrieve personal space: %w", err) + } + if lspr.GetStatus().GetCode() != cs3rpc.Code_CODE_OK { + return nil, fmt.Errorf("failed to retrieve personal space: %s", lspr.GetStatus().GetMessage()) + } + if len(lspr.GetStorageSpaces()) > 1 { + return nil, errors.New("retrieved more than one personal space") + } + if len(lspr.GetStorageSpaces()) != 1 { + return nil, ErrNotFound + } + return lspr.GetStorageSpaces()[0], nil +} + +func listStorageSpacesUserFilter(id string) *storageprovider.ListStorageSpacesRequest_Filter { + return &storageprovider.ListStorageSpacesRequest_Filter{ + Type: storageprovider.ListStorageSpacesRequest_Filter_TYPE_USER, + Term: &storageprovider.ListStorageSpacesRequest_Filter_User{ + User: &userv1beta1.UserId{ + OpaqueId: id, + }, + }, + } +} + +func listStorageSpacesTypeFilter(spaceType string) *storageprovider.ListStorageSpacesRequest_Filter { + return &storageprovider.ListStorageSpacesRequest_Filter{ + Type: storageprovider.ListStorageSpacesRequest_Filter_TYPE_SPACE_TYPE, + Term: &storageprovider.ListStorageSpacesRequest_Filter_SpaceType{ + SpaceType: spaceType, + }, + } +} + +func isTrashed(sp *storageprovider.StorageSpace) bool { + return utils.ReadPlainFromOpaque(sp.GetOpaque(), _spaceStateTrashed) == _spaceStateTrashed +} diff --git a/ocis-pkg/shared/storage_utils_test.go b/ocis-pkg/shared/storage_utils_test.go new file mode 100644 index 00000000000..c3f22d72f5a --- /dev/null +++ b/ocis-pkg/shared/storage_utils_test.go @@ -0,0 +1,195 @@ +package shared + +import ( + "context" + "errors" + "testing" + + cs3rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1" + storageprovider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" + types "github.com/cs3org/go-cs3apis/cs3/types/v1beta1" + libregraph "github.com/owncloud/libre-graph-api-go" + cs3mocks "github.com/owncloud/reva/v2/tests/cs3mocks/mocks" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" +) + +func okStatus() *cs3rpc.Status { + return &cs3rpc.Status{Code: cs3rpc.Code_CODE_OK} +} + +func status(code cs3rpc.Code, msg string) *cs3rpc.Status { + return &cs3rpc.Status{Code: code, Message: msg} +} + +func newSpace(id string, trashed bool) *storageprovider.StorageSpace { + sp := &storageprovider.StorageSpace{ + Id: &storageprovider.StorageSpaceId{OpaqueId: id}, + Root: nil, + } + if trashed { + sp.Opaque = &types.Opaque{ + Map: map[string]*types.OpaqueEntry{ + _spaceStateTrashed: {Decoder: "plain", Value: []byte(_spaceStateTrashed)}, + }, + } + } + return sp +} + +func TestEnsurePersonalSpace(t *testing.T) { + t.Run("no-op when personal space exists and is active", func(t *testing.T) { + gw := cs3mocks.NewGatewayAPIClient(t) + gw.EXPECT().ListStorageSpaces(mock.Anything, mock.Anything, mock.Anything).Return(&storageprovider.ListStorageSpacesResponse{ + Status: okStatus(), + StorageSpaces: []*storageprovider.StorageSpace{newSpace("ps1", false)}, + }, nil).Once() + + user := libregraph.NewUser("User One", "user1") + user.SetId("user1") + + err := EnsurePersonalSpace(context.Background(), gw, *user) + require.NoError(t, err) + }) + + t.Run("restores trashed personal space", func(t *testing.T) { + gw := cs3mocks.NewGatewayAPIClient(t) + sp := newSpace("ps2", true) + + gw.EXPECT().ListStorageSpaces(mock.Anything, mock.Anything, mock.Anything).Return(&storageprovider.ListStorageSpacesResponse{ + Status: okStatus(), + StorageSpaces: []*storageprovider.StorageSpace{sp}, + }, nil).Once() + + gw.EXPECT().UpdateStorageSpace(mock.Anything, mock.Anything, mock.Anything).Return(&storageprovider.UpdateStorageSpaceResponse{ + Status: okStatus(), + }, nil).Once() + + user := libregraph.NewUser("User Two", "user2") + user.SetId("user2") + + err := EnsurePersonalSpace(context.Background(), gw, *user) + require.NoError(t, err) + }) + + t.Run("creates when not found", func(t *testing.T) { + gw := cs3mocks.NewGatewayAPIClient(t) + gw.EXPECT().ListStorageSpaces(mock.Anything, mock.Anything, mock.Anything).Return(&storageprovider.ListStorageSpacesResponse{ + Status: okStatus(), + StorageSpaces: []*storageprovider.StorageSpace{}, + }, nil).Once() + + gw.EXPECT().CreateStorageSpace(mock.Anything, mock.Anything, mock.Anything).Return(&storageprovider.CreateStorageSpaceResponse{ + Status: okStatus(), + }, nil).Once() + + user := libregraph.NewUser("User Three", "user3") + user.SetId("user3") + + err := EnsurePersonalSpace(context.Background(), gw, *user) + require.NoError(t, err) + }) + + t.Run("create returns already exists treated as success", func(t *testing.T) { + gw := cs3mocks.NewGatewayAPIClient(t) + gw.EXPECT().ListStorageSpaces(mock.Anything, mock.Anything, mock.Anything).Return(&storageprovider.ListStorageSpacesResponse{ + Status: okStatus(), + StorageSpaces: []*storageprovider.StorageSpace{}, + }, nil).Once() + + gw.EXPECT().CreateStorageSpace(mock.Anything, mock.Anything, mock.Anything).Return(&storageprovider.CreateStorageSpaceResponse{ + Status: status(cs3rpc.Code_CODE_ALREADY_EXISTS, "exists"), + }, nil).Once() + + user := libregraph.NewUser("User Four", "user4") + user.SetId("user4") + + err := EnsurePersonalSpace(context.Background(), gw, *user) + require.NoError(t, err) + }) + + t.Run("propagates list error", func(t *testing.T) { + gw := cs3mocks.NewGatewayAPIClient(t) + gw.EXPECT().ListStorageSpaces(mock.Anything, mock.Anything, mock.Anything).Return(nil, errors.New("boom")).Once() + + user := libregraph.NewUser("User Five", "user5") + user.SetId("user5") + + err := EnsurePersonalSpace(context.Background(), gw, *user) + require.Error(t, err) + }) + + t.Run("propagates non-ok update status", func(t *testing.T) { + gw := cs3mocks.NewGatewayAPIClient(t) + sp := newSpace("ps3", true) + + gw.EXPECT().ListStorageSpaces(mock.Anything, mock.Anything, mock.Anything).Return(&storageprovider.ListStorageSpacesResponse{ + Status: okStatus(), + StorageSpaces: []*storageprovider.StorageSpace{sp}, + }, nil).Once() + + gw.EXPECT().UpdateStorageSpace(mock.Anything, mock.Anything, mock.Anything).Return(&storageprovider.UpdateStorageSpaceResponse{ + Status: status(cs3rpc.Code_CODE_INVALID_ARGUMENT, "nope"), + }, nil).Once() + + user := libregraph.NewUser("User Six", "user6") + user.SetId("user6") + + err := EnsurePersonalSpace(context.Background(), gw, *user) + require.Error(t, err) + }) +} + +func TestDisablePersonalSpace(t *testing.T) { + t.Run("no-op when personal space already trashed", func(t *testing.T) { + gw := cs3mocks.NewGatewayAPIClient(t) + sp := newSpace("ps4", true) + gw.EXPECT().ListStorageSpaces(mock.Anything, mock.Anything, mock.Anything).Return(&storageprovider.ListStorageSpacesResponse{ + Status: okStatus(), + StorageSpaces: []*storageprovider.StorageSpace{sp}, + }, nil).Once() + + err := DisablePersonalSpace(context.Background(), gw, "user1") + require.NoError(t, err) + }) + + t.Run("deletes active personal space", func(t *testing.T) { + gw := cs3mocks.NewGatewayAPIClient(t) + sp := newSpace("ps5", false) + gw.EXPECT().ListStorageSpaces(mock.Anything, mock.Anything, mock.Anything).Return(&storageprovider.ListStorageSpacesResponse{ + Status: okStatus(), + StorageSpaces: []*storageprovider.StorageSpace{sp}, + }, nil).Once() + + gw.EXPECT().DeleteStorageSpace(mock.Anything, mock.Anything, mock.Anything).Return(&storageprovider.DeleteStorageSpaceResponse{ + Status: okStatus(), + }, nil).Once() + + err := DisablePersonalSpace(context.Background(), gw, "user1") + require.NoError(t, err) + }) + + t.Run("propagates non-ok delete status", func(t *testing.T) { + gw := cs3mocks.NewGatewayAPIClient(t) + sp := newSpace("ps6", false) + gw.EXPECT().ListStorageSpaces(mock.Anything, mock.Anything, mock.Anything).Return(&storageprovider.ListStorageSpacesResponse{ + Status: okStatus(), + StorageSpaces: []*storageprovider.StorageSpace{sp}, + }, nil).Once() + + gw.EXPECT().DeleteStorageSpace(mock.Anything, mock.Anything, mock.Anything).Return(&storageprovider.DeleteStorageSpaceResponse{ + Status: status(cs3rpc.Code_CODE_INTERNAL, "fail"), + }, nil).Once() + + err := DisablePersonalSpace(context.Background(), gw, "user1") + require.Error(t, err) + }) + + t.Run("propagates list error", func(t *testing.T) { + gw := cs3mocks.NewGatewayAPIClient(t) + gw.EXPECT().ListStorageSpaces(mock.Anything, mock.Anything, mock.Anything).Return(nil, errors.New("boom")).Once() + + err := DisablePersonalSpace(context.Background(), gw, "user1") + require.Error(t, err) + }) +} diff --git a/services/graph/pkg/errorcode/errorcode.go b/services/graph/pkg/errorcode/errorcode.go index 297c334e101..f18b4816428 100644 --- a/services/graph/pkg/errorcode/errorcode.go +++ b/services/graph/pkg/errorcode/errorcode.go @@ -7,6 +7,7 @@ import ( "net/http" "time" + rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1" "github.com/go-chi/chi/v5/middleware" "github.com/go-chi/render" libregraph "github.com/owncloud/libre-graph-api-go" @@ -106,6 +107,11 @@ func New(e ErrorCode, msg string) Error { } } +// New errorcode.Error from cs3rpc Status Code +func NewFromStatusCode(code rpc.Code, msg string) Error { + return New(cs3StatusToErrCode(code), msg) +} + // Render writes a Graph ErrorCode object to the response writer func (e ErrorCode) Render(w http.ResponseWriter, r *http.Request, status int, msg string) { render.Status(r, status) @@ -206,3 +212,23 @@ func ToError(err error) (Error, bool) { return Error{}, false } + +func cs3StatusToErrCode(code rpc.Code) (errcode ErrorCode) { + switch code { + case rpc.Code_CODE_UNAUTHENTICATED: + errcode = Unauthenticated + case rpc.Code_CODE_PERMISSION_DENIED: + errcode = AccessDenied + case rpc.Code_CODE_NOT_FOUND: + errcode = ItemNotFound + case rpc.Code_CODE_LOCKED: + errcode = ItemIsLocked + case rpc.Code_CODE_INVALID_ARGUMENT: + errcode = InvalidRequest + case rpc.Code_CODE_FAILED_PRECONDITION: + errcode = InvalidRequest + default: + errcode = GeneralException + } + return errcode +} diff --git a/services/graph/pkg/service/v0/api_driveitem_permissions_links.go b/services/graph/pkg/service/v0/api_driveitem_permissions_links.go index 68e888be90b..bb657b95b90 100644 --- a/services/graph/pkg/service/v0/api_driveitem_permissions_links.go +++ b/services/graph/pkg/service/v0/api_driveitem_permissions_links.go @@ -41,7 +41,7 @@ func (s DriveItemPermissionsService) CreateLink(ctx context.Context, driveItemID } if code := statResp.GetStatus().GetCode(); code != rpc.Code_CODE_OK { s.logger.Debug().Interface("itemID", driveItemID).Msg(statResp.GetStatus().GetMessage()) - return libregraph.Permission{}, errorcode.New(cs3StatusToErrCode(code), statResp.GetStatus().GetMessage()) + return libregraph.Permission{}, errorcode.NewFromStatusCode(code, statResp.GetStatus().GetMessage()) } permissions, err := linktype.CS3ResourcePermissionsFromSharingLink(createLink, statResp.GetInfo().GetType()) if err != nil { @@ -83,7 +83,7 @@ func (s DriveItemPermissionsService) CreateLink(ctx context.Context, driveItemID return libregraph.Permission{}, errorcode.New(errorcode.GeneralException, err.Error()) } if statusCode := createResp.GetStatus().GetCode(); statusCode != rpc.Code_CODE_OK { - return libregraph.Permission{}, errorcode.New(cs3StatusToErrCode(statusCode), createResp.Status.Message) + return libregraph.Permission{}, errorcode.NewFromStatusCode(statusCode, createResp.Status.Message) } link := createResp.GetShare() perm, err := s.libreGraphPermissionFromCS3PublicShare(link) diff --git a/services/graph/pkg/service/v0/approleassignments.go b/services/graph/pkg/service/v0/approleassignments.go index b64c91df6a6..3b2ee6c218a 100644 --- a/services/graph/pkg/service/v0/approleassignments.go +++ b/services/graph/pkg/service/v0/approleassignments.go @@ -7,9 +7,11 @@ import ( "github.com/go-chi/chi/v5" "github.com/go-chi/render" libregraph "github.com/owncloud/libre-graph-api-go" + "github.com/owncloud/ocis/v2/ocis-pkg/shared" settingsmsg "github.com/owncloud/ocis/v2/protogen/gen/ocis/messages/settings/v0" settingssvc "github.com/owncloud/ocis/v2/protogen/gen/ocis/services/settings/v0" "github.com/owncloud/ocis/v2/services/graph/pkg/errorcode" + settingsService "github.com/owncloud/ocis/v2/services/settings/pkg/service/v0" revactx "github.com/owncloud/reva/v2/pkg/ctx" "github.com/owncloud/reva/v2/pkg/events" "github.com/owncloud/reva/v2/pkg/utils" @@ -73,7 +75,7 @@ func (g Graph) CreateAppRoleAssignment(w http.ResponseWriter, r *http.Request) { artur, err := g.roleService.AssignRoleToUser(r.Context(), &settingssvc.AssignRoleToUserRequest{ AccountUuid: userID, - RoleId: appRoleAssignment.AppRoleId, + RoleId: appRoleAssignment.GetAppRoleId(), }) if err != nil { if merr, ok := merrors.As(err); ok && merr.Code == http.StatusForbidden { @@ -84,10 +86,38 @@ func (g Graph) CreateAppRoleAssignment(w http.ResponseWriter, r *http.Request) { return } - var role string + var oldRole string roles := oldRoles.GetAssignments() if len(roles) > 0 { - role = roles[0].GetRoleId() + oldRole = roles[0].GetRoleId() + } + + client, err := g.gatewaySelector.Next() + if err != nil { + errorcode.NotAllowed.Render(w, r, http.StatusForbidden, err.Error()) + return + } + + if appRoleAssignment.GetAppRoleId() == settingsService.BundleUUIDRoleUserLight { + err := shared.DisablePersonalSpace(r.Context(), client, userID) + if err != nil { + logger.Error().Any("userID", userID).Err(err).Msg("can't disable the personal space") + errorcode.RenderError(w, r, err) + return + } + } + if appRoleAssignment.GetAppRoleId() != settingsService.BundleUUIDRoleUserLight { + user, err := g.identityCache.GetUser(r.Context(), userID) + if err != nil { + errorcode.RenderError(w, r, fmt.Errorf("failed to get user: %w", err)) + return + } + err = shared.EnsurePersonalSpace(r.Context(), client, user) + if err != nil { + logger.Error().Any("userID", userID).Err(err).Msg("can't ensure the personal space") + errorcode.RenderError(w, r, err) + return + } } e := events.UserFeatureChanged{ @@ -96,7 +126,7 @@ func (g Graph) CreateAppRoleAssignment(w http.ResponseWriter, r *http.Request) { { Name: "roleChanged", Value: appRoleAssignment.AppRoleId, - OldValue: &role, + OldValue: &oldRole, }, }, Timestamp: utils.TSNow(), diff --git a/services/graph/pkg/service/v0/approleassignments_test.go b/services/graph/pkg/service/v0/approleassignments_test.go index d9fbda8d024..a4ef9a8ec3d 100644 --- a/services/graph/pkg/service/v0/approleassignments_test.go +++ b/services/graph/pkg/service/v0/approleassignments_test.go @@ -4,12 +4,15 @@ import ( "bytes" "context" "encoding/json" + "fmt" "io" "net/http" "net/http/httptest" gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1" userv1beta1 "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" + rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1" + storageprovider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" "github.com/go-chi/chi/v5" "github.com/golang/protobuf/ptypes/empty" . "github.com/onsi/ginkgo/v2" @@ -23,10 +26,12 @@ import ( "github.com/owncloud/ocis/v2/services/graph/pkg/config/defaults" identitymocks "github.com/owncloud/ocis/v2/services/graph/pkg/identity/mocks" service "github.com/owncloud/ocis/v2/services/graph/pkg/service/v0" + settingsService "github.com/owncloud/ocis/v2/services/settings/pkg/service/v0" revactx "github.com/owncloud/reva/v2/pkg/ctx" "github.com/owncloud/reva/v2/pkg/rgrpc/todo/pool" cs3mocks "github.com/owncloud/reva/v2/tests/cs3mocks/mocks" "github.com/stretchr/testify/mock" + merrors "go-micro.dev/v4/errors" "google.golang.org/grpc" ) @@ -70,6 +75,18 @@ var _ = Describe("AppRoleAssignments", func() { }, ) + gatewayClient.On("GetUser", mock.Anything, mock.Anything).Return(&userv1beta1.GetUserResponse{ + Status: &rpc.Status{Code: rpc.Code_CODE_OK}, + User: currentUser, + }, nil) + + gatewayClient.On("ListStorageSpaces", mock.Anything, mock.Anything).Return(&storageprovider.ListStorageSpacesResponse{ + Status: &rpc.Status{Code: rpc.Code_CODE_OK}, + StorageSpaces: []*storageprovider.StorageSpace{ + {Id: &storageprovider.StorageSpaceId{OpaqueId: "ps1"}}, + }, + }, nil) + rr = httptest.NewRecorder() ctx = context.Background() @@ -173,6 +190,316 @@ var _ = Describe("AppRoleAssignments", func() { Expect(assignment.GetResourceId()).To(Equal(cfg.Application.ID)) }) + It("returns bad request for invalid JSON", func() { + invalidJson := `{"invalid": json}` + r := httptest.NewRequest(http.MethodPost, "/graph/v1.0/users/user1/appRoleAssignments", bytes.NewBufferString(invalidJson)) + rctx := chi.NewRouteContext() + rctx.URLParams.Add("userID", "user1") + r = r.WithContext(context.WithValue(revactx.ContextSetUser(ctx, currentUser), chi.RouteCtxKey, rctx)) + svc.CreateAppRoleAssignment(rr, r) + + Expect(rr.Code).To(Equal(http.StatusBadRequest)) + }) + + It("returns bad request when principal ID does not match user ID", func() { + roleService.On("ListRoleAssignments", mock.Anything, mock.Anything, mock.Anything).Return(&settings.ListRoleAssignmentsResponse{Assignments: []*settingsmsg.UserRoleAssignment{}}, nil) + + ara := libregraph.NewAppRoleAssignmentWithDefaults() + ara.SetAppRoleId("some-appRole-ID") + ara.SetPrincipalId("different-user-id") + ara.SetResourceId(cfg.Application.ID) + + araJson, err := json.Marshal(ara) + Expect(err).ToNot(HaveOccurred()) + + r := httptest.NewRequest(http.MethodPost, "/graph/v1.0/users/user1/appRoleAssignments", bytes.NewBuffer(araJson)) + rctx := chi.NewRouteContext() + rctx.URLParams.Add("userID", "user1") + r = r.WithContext(context.WithValue(revactx.ContextSetUser(ctx, currentUser), chi.RouteCtxKey, rctx)) + svc.CreateAppRoleAssignment(rr, r) + + Expect(rr.Code).To(Equal(http.StatusBadRequest)) + }) + + It("returns bad request when resource ID does not match application ID", func() { + roleService.On("ListRoleAssignments", mock.Anything, mock.Anything, mock.Anything).Return(&settings.ListRoleAssignmentsResponse{Assignments: []*settingsmsg.UserRoleAssignment{}}, nil) + + ara := libregraph.NewAppRoleAssignmentWithDefaults() + ara.SetAppRoleId("some-appRole-ID") + ara.SetPrincipalId("user1") + ara.SetResourceId("different-application-id") + + araJson, err := json.Marshal(ara) + Expect(err).ToNot(HaveOccurred()) + + r := httptest.NewRequest(http.MethodPost, "/graph/v1.0/users/user1/appRoleAssignments", bytes.NewBuffer(araJson)) + rctx := chi.NewRouteContext() + rctx.URLParams.Add("userID", "user1") + r = r.WithContext(context.WithValue(revactx.ContextSetUser(ctx, currentUser), chi.RouteCtxKey, rctx)) + svc.CreateAppRoleAssignment(rr, r) + + Expect(rr.Code).To(Equal(http.StatusBadRequest)) + }) + + It("returns forbidden when AssignRoleToUser returns forbidden error", func() { + roleService.On("ListRoleAssignments", mock.Anything, mock.Anything, mock.Anything).Return(&settings.ListRoleAssignmentsResponse{Assignments: []*settingsmsg.UserRoleAssignment{}}, nil) + roleService.On("AssignRoleToUser", mock.Anything, mock.Anything, mock.Anything).Return(nil, merrors.Forbidden("test", "forbidden")) + + ara := libregraph.NewAppRoleAssignmentWithDefaults() + ara.SetAppRoleId("some-appRole-ID") + ara.SetPrincipalId("user1") + ara.SetResourceId(cfg.Application.ID) + + araJson, err := json.Marshal(ara) + Expect(err).ToNot(HaveOccurred()) + + r := httptest.NewRequest(http.MethodPost, "/graph/v1.0/users/user1/appRoleAssignments", bytes.NewBuffer(araJson)) + rctx := chi.NewRouteContext() + rctx.URLParams.Add("userID", "user1") + r = r.WithContext(context.WithValue(revactx.ContextSetUser(ctx, currentUser), chi.RouteCtxKey, rctx)) + svc.CreateAppRoleAssignment(rr, r) + + Expect(rr.Code).To(Equal(http.StatusForbidden)) + }) + + It("returns internal server error when AssignRoleToUser returns general error", func() { + roleService.On("ListRoleAssignments", mock.Anything, mock.Anything, mock.Anything).Return(&settings.ListRoleAssignmentsResponse{Assignments: []*settingsmsg.UserRoleAssignment{}}, nil) + roleService.On("AssignRoleToUser", mock.Anything, mock.Anything, mock.Anything).Return(nil, fmt.Errorf("general error")) + + ara := libregraph.NewAppRoleAssignmentWithDefaults() + ara.SetAppRoleId("some-appRole-ID") + ara.SetPrincipalId("user1") + ara.SetResourceId(cfg.Application.ID) + + araJson, err := json.Marshal(ara) + Expect(err).ToNot(HaveOccurred()) + + r := httptest.NewRequest(http.MethodPost, "/graph/v1.0/users/user1/appRoleAssignments", bytes.NewBuffer(araJson)) + rctx := chi.NewRouteContext() + rctx.URLParams.Add("userID", "user1") + r = r.WithContext(context.WithValue(revactx.ContextSetUser(ctx, currentUser), chi.RouteCtxKey, rctx)) + svc.CreateAppRoleAssignment(rr, r) + + Expect(rr.Code).To(Equal(http.StatusInternalServerError)) + }) + + It("disables personal space for UserLight role", func() { + userRoleAssignment := &settingsmsg.UserRoleAssignment{ + Id: "some-appRoleAssignment-ID", + AccountUuid: "user1", + RoleId: settingsService.BundleUUIDRoleUserLight, + } + roleService.On("ListRoleAssignments", mock.Anything, mock.Anything, mock.Anything).Return(&settings.ListRoleAssignmentsResponse{Assignments: []*settingsmsg.UserRoleAssignment{}}, nil) + roleService.On("AssignRoleToUser", mock.Anything, mock.Anything, mock.Anything).Return(&settings.AssignRoleToUserResponse{Assignment: userRoleAssignment}, nil) + + gatewayClient.On("ListStorageSpaces", mock.Anything, mock.Anything).Return(&storageprovider.ListStorageSpacesResponse{ + Status: &rpc.Status{Code: rpc.Code_CODE_OK}, + StorageSpaces: []*storageprovider.StorageSpace{ + {Id: &storageprovider.StorageSpaceId{OpaqueId: "ps1"}}, + }, + }, nil) + gatewayClient.On("DeleteStorageSpace", mock.Anything, mock.Anything).Return(&storageprovider.DeleteStorageSpaceResponse{ + Status: &rpc.Status{Code: rpc.Code_CODE_OK}, + }, nil) + + ara := libregraph.NewAppRoleAssignmentWithDefaults() + ara.SetAppRoleId(settingsService.BundleUUIDRoleUserLight) + ara.SetPrincipalId("user1") + ara.SetResourceId(cfg.Application.ID) + + araJson, err := json.Marshal(ara) + Expect(err).ToNot(HaveOccurred()) + + r := httptest.NewRequest(http.MethodPost, "/graph/v1.0/users/user1/appRoleAssignments", bytes.NewBuffer(araJson)) + rctx := chi.NewRouteContext() + rctx.URLParams.Add("userID", "user1") + r = r.WithContext(context.WithValue(revactx.ContextSetUser(ctx, currentUser), chi.RouteCtxKey, rctx)) + svc.CreateAppRoleAssignment(rr, r) + + Expect(rr.Code).To(Equal(http.StatusCreated)) + }) + + It("ensures personal space for non-UserLight role", func() { + userRoleAssignment := &settingsmsg.UserRoleAssignment{ + Id: "some-appRoleAssignment-ID", + AccountUuid: "user1", + RoleId: "some-appRole-ID", + } + roleService.On("ListRoleAssignments", mock.Anything, mock.Anything, mock.Anything).Return(&settings.ListRoleAssignmentsResponse{Assignments: []*settingsmsg.UserRoleAssignment{}}, nil) + roleService.On("AssignRoleToUser", mock.Anything, mock.Anything, mock.Anything).Return(&settings.AssignRoleToUserResponse{Assignment: userRoleAssignment}, nil) + + gatewayClient.On("ListStorageSpaces", mock.Anything, mock.Anything).Return(&storageprovider.ListStorageSpacesResponse{ + Status: &rpc.Status{Code: rpc.Code_CODE_OK}, + StorageSpaces: []*storageprovider.StorageSpace{}, + }, nil) + gatewayClient.On("CreateStorageSpace", mock.Anything, mock.Anything).Return(&storageprovider.CreateStorageSpaceResponse{ + Status: &rpc.Status{Code: rpc.Code_CODE_OK}, + }, nil) + + ara := libregraph.NewAppRoleAssignmentWithDefaults() + ara.SetAppRoleId("some-appRole-ID") + ara.SetPrincipalId("user1") + ara.SetResourceId(cfg.Application.ID) + + araJson, err := json.Marshal(ara) + Expect(err).ToNot(HaveOccurred()) + + r := httptest.NewRequest(http.MethodPost, "/graph/v1.0/users/user1/appRoleAssignments", bytes.NewBuffer(araJson)) + rctx := chi.NewRouteContext() + rctx.URLParams.Add("userID", "user1") + r = r.WithContext(context.WithValue(revactx.ContextSetUser(ctx, currentUser), chi.RouteCtxKey, rctx)) + svc.CreateAppRoleAssignment(rr, r) + + Expect(rr.Code).To(Equal(http.StatusCreated)) + }) + + It("handles old role assignment correctly", func() { + oldRoleAssignment := &settingsmsg.UserRoleAssignment{ + Id: "old-assignment-ID", + AccountUuid: "user1", + RoleId: "old-role-ID", + } + userRoleAssignment := &settingsmsg.UserRoleAssignment{ + Id: "some-appRoleAssignment-ID", + AccountUuid: "user1", + RoleId: "some-appRole-ID", + } + roleService.On("ListRoleAssignments", mock.Anything, mock.Anything, mock.Anything).Return(&settings.ListRoleAssignmentsResponse{ + Assignments: []*settingsmsg.UserRoleAssignment{oldRoleAssignment}, + }, nil) + roleService.On("AssignRoleToUser", mock.Anything, mock.Anything, mock.Anything).Return(&settings.AssignRoleToUserResponse{Assignment: userRoleAssignment}, nil) + + gatewayClient.On("ListStorageSpaces", mock.Anything, mock.Anything).Return(&storageprovider.ListStorageSpacesResponse{ + Status: &rpc.Status{Code: rpc.Code_CODE_OK}, + StorageSpaces: []*storageprovider.StorageSpace{}, + }, nil) + gatewayClient.On("CreateStorageSpace", mock.Anything, mock.Anything).Return(&storageprovider.CreateStorageSpaceResponse{ + Status: &rpc.Status{Code: rpc.Code_CODE_OK}, + }, nil) + + ara := libregraph.NewAppRoleAssignmentWithDefaults() + ara.SetAppRoleId("some-appRole-ID") + ara.SetPrincipalId("user1") + ara.SetResourceId(cfg.Application.ID) + + araJson, err := json.Marshal(ara) + Expect(err).ToNot(HaveOccurred()) + + r := httptest.NewRequest(http.MethodPost, "/graph/v1.0/users/user1/appRoleAssignments", bytes.NewBuffer(araJson)) + rctx := chi.NewRouteContext() + rctx.URLParams.Add("userID", "user1") + r = r.WithContext(context.WithValue(revactx.ContextSetUser(ctx, currentUser), chi.RouteCtxKey, rctx)) + svc.CreateAppRoleAssignment(rr, r) + + Expect(rr.Code).To(Equal(http.StatusCreated)) + }) + + It("returns error when DisablePersonalSpace fails for UserLight role", func() { + userRoleAssignment := &settingsmsg.UserRoleAssignment{ + Id: "some-appRoleAssignment-ID", + AccountUuid: "user1", + RoleId: settingsService.BundleUUIDRoleUserLight, + } + roleService.On("ListRoleAssignments", mock.Anything, mock.Anything, mock.Anything).Return(&settings.ListRoleAssignmentsResponse{Assignments: []*settingsmsg.UserRoleAssignment{}}, nil) + roleService.On("AssignRoleToUser", mock.Anything, mock.Anything, mock.Anything).Return(&settings.AssignRoleToUserResponse{Assignment: userRoleAssignment}, nil) + + gatewayClient.On("ListStorageSpaces", mock.Anything, mock.Anything).Return(&storageprovider.ListStorageSpacesResponse{ + Status: &rpc.Status{Code: rpc.Code_CODE_OK}, + StorageSpaces: []*storageprovider.StorageSpace{ + {Id: &storageprovider.StorageSpaceId{OpaqueId: "ps1"}}, + }, + }, nil) + gatewayClient.On("DeleteStorageSpace", mock.Anything, mock.Anything).Return(&storageprovider.DeleteStorageSpaceResponse{ + Status: &rpc.Status{Code: rpc.Code_CODE_INTERNAL, Message: "internal error"}, + }, nil) + + ara := libregraph.NewAppRoleAssignmentWithDefaults() + ara.SetAppRoleId(settingsService.BundleUUIDRoleUserLight) + ara.SetPrincipalId("user1") + ara.SetResourceId(cfg.Application.ID) + + araJson, err := json.Marshal(ara) + Expect(err).ToNot(HaveOccurred()) + + r := httptest.NewRequest(http.MethodPost, "/graph/v1.0/users/user1/appRoleAssignments", bytes.NewBuffer(araJson)) + rctx := chi.NewRouteContext() + rctx.URLParams.Add("userID", "user1") + r = r.WithContext(context.WithValue(revactx.ContextSetUser(ctx, currentUser), chi.RouteCtxKey, rctx)) + svc.CreateAppRoleAssignment(rr, r) + + Expect(rr.Code).To(Equal(http.StatusInternalServerError)) + }) + + It("returns error when GetUser fails for non-UserLight role", func() { + userRoleAssignment := &settingsmsg.UserRoleAssignment{ + Id: "some-appRoleAssignment-ID", + AccountUuid: "user1", + RoleId: "some-appRole-ID", + } + roleService.On("ListRoleAssignments", mock.Anything, mock.Anything, mock.Anything).Return(&settings.ListRoleAssignmentsResponse{Assignments: []*settingsmsg.UserRoleAssignment{}}, nil) + roleService.On("AssignRoleToUser", mock.Anything, mock.Anything, mock.Anything).Return(&settings.AssignRoleToUserResponse{Assignment: userRoleAssignment}, nil) + + // Reset the mock and make GetUser fail + gatewayClient.ExpectedCalls = nil + gatewayClient.On("GetUser", mock.Anything, mock.Anything).Return(nil, fmt.Errorf("user not found")) + + ara := libregraph.NewAppRoleAssignmentWithDefaults() + ara.SetAppRoleId("some-appRole-ID") + ara.SetPrincipalId("user1") + ara.SetResourceId(cfg.Application.ID) + + araJson, err := json.Marshal(ara) + Expect(err).ToNot(HaveOccurred()) + + r := httptest.NewRequest(http.MethodPost, "/graph/v1.0/users/user1/appRoleAssignments", bytes.NewBuffer(araJson)) + rctx := chi.NewRouteContext() + rctx.URLParams.Add("userID", "user1") + r = r.WithContext(context.WithValue(revactx.ContextSetUser(ctx, currentUser), chi.RouteCtxKey, rctx)) + svc.CreateAppRoleAssignment(rr, r) + + Expect(rr.Code).To(Equal(http.StatusInternalServerError)) + }) + + It("returns error when EnsurePersonalSpace fails for non-UserLight role", func() { + userRoleAssignment := &settingsmsg.UserRoleAssignment{ + Id: "some-appRoleAssignment-ID", + AccountUuid: "user1", + RoleId: "some-appRole-ID", + } + roleService.On("ListRoleAssignments", mock.Anything, mock.Anything, mock.Anything).Return(&settings.ListRoleAssignmentsResponse{Assignments: []*settingsmsg.UserRoleAssignment{}}, nil) + roleService.On("AssignRoleToUser", mock.Anything, mock.Anything, mock.Anything).Return(&settings.AssignRoleToUserResponse{Assignment: userRoleAssignment}, nil) + + // Reset the mock and set up the failing scenario + gatewayClient.ExpectedCalls = nil + gatewayClient.On("GetUser", mock.Anything, mock.Anything).Return(&userv1beta1.GetUserResponse{ + Status: &rpc.Status{Code: rpc.Code_CODE_OK}, + User: currentUser, + }, nil) + gatewayClient.On("ListStorageSpaces", mock.Anything, mock.Anything).Return(&storageprovider.ListStorageSpacesResponse{ + Status: &rpc.Status{Code: rpc.Code_CODE_OK}, + StorageSpaces: []*storageprovider.StorageSpace{}, + }, nil) + gatewayClient.On("CreateStorageSpace", mock.Anything, mock.Anything).Return(&storageprovider.CreateStorageSpaceResponse{ + Status: &rpc.Status{Code: rpc.Code_CODE_INTERNAL, Message: "internal error"}, + }, nil) + + ara := libregraph.NewAppRoleAssignmentWithDefaults() + ara.SetAppRoleId("some-appRole-ID") + ara.SetPrincipalId("user1") + ara.SetResourceId(cfg.Application.ID) + + araJson, err := json.Marshal(ara) + Expect(err).ToNot(HaveOccurred()) + + r := httptest.NewRequest(http.MethodPost, "/graph/v1.0/users/user1/appRoleAssignments", bytes.NewBuffer(araJson)) + rctx := chi.NewRouteContext() + rctx.URLParams.Add("userID", "user1") + r = r.WithContext(context.WithValue(revactx.ContextSetUser(ctx, currentUser), chi.RouteCtxKey, rctx)) + svc.CreateAppRoleAssignment(rr, r) + + Expect(rr.Code).To(Equal(http.StatusInternalServerError)) + }) + }) Describe("DeleteAppRoleAssignment", func() { diff --git a/services/graph/pkg/service/v0/base.go b/services/graph/pkg/service/v0/base.go index 00ae6281f72..4481dab5244 100644 --- a/services/graph/pkg/service/v0/base.go +++ b/services/graph/pkg/service/v0/base.go @@ -283,7 +283,7 @@ func (g BaseGraphService) listUserShares(ctx context.Context, filters []*collabo return driveItems, errorcode.New(errorcode.GeneralException, err.Error()) } if statusCode := lsUserSharesResponse.GetStatus().GetCode(); statusCode != rpc.Code_CODE_OK { - return driveItems, errorcode.New(cs3StatusToErrCode(statusCode), lsUserSharesResponse.Status.Message) + return driveItems, errorcode.NewFromStatusCode(statusCode, lsUserSharesResponse.Status.Message) } driveItems, err = g.cs3UserSharesToDriveItems(ctx, lsUserSharesResponse.Shares, driveItems) if err != nil { @@ -311,7 +311,7 @@ func (g BaseGraphService) listOCMShares(ctx context.Context, filters []*ocm.List return driveItems, errorcode.New(errorcode.GeneralException, err.Error()) } if statusCode := lsOCMSharesResponse.GetStatus().GetCode(); statusCode != rpc.Code_CODE_OK { - return driveItems, errorcode.New(cs3StatusToErrCode(statusCode), lsOCMSharesResponse.Status.Message) + return driveItems, errorcode.NewFromStatusCode(statusCode, lsOCMSharesResponse.Status.Message) } driveItems, err = g.cs3OCMSharesToDriveItems(ctx, lsOCMSharesResponse.Shares, driveItems) if err != nil { @@ -340,7 +340,7 @@ func (g BaseGraphService) listPublicShares(ctx context.Context, filters []*link. return driveItems, errorcode.New(errorcode.GeneralException, err.Error()) } if statusCode := lsPublicSharesResponse.GetStatus().GetCode(); statusCode != rpc.Code_CODE_OK { - return driveItems, errorcode.New(cs3StatusToErrCode(statusCode), lsPublicSharesResponse.Status.Message) + return driveItems, errorcode.NewFromStatusCode(statusCode, lsPublicSharesResponse.Status.Message) } driveItems, err = g.cs3PublicSharesToDriveItems(ctx, lsPublicSharesResponse.Share, driveItems) if err != nil { diff --git a/services/graph/pkg/service/v0/sharedbyme.go b/services/graph/pkg/service/v0/sharedbyme.go index 22a9be3026e..0daf1fa2e6d 100644 --- a/services/graph/pkg/service/v0/sharedbyme.go +++ b/services/graph/pkg/service/v0/sharedbyme.go @@ -3,7 +3,6 @@ package svc import ( "net/http" - rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1" "github.com/go-chi/render" libregraph "github.com/owncloud/libre-graph-api-go" @@ -47,23 +46,3 @@ func (g Graph) GetSharedByMe(w http.ResponseWriter, r *http.Request) { render.Status(r, http.StatusOK) render.JSON(w, r, &ListResponse{Value: res}) } - -func cs3StatusToErrCode(code rpc.Code) (errcode errorcode.ErrorCode) { - switch code { - case rpc.Code_CODE_UNAUTHENTICATED: - errcode = errorcode.Unauthenticated - case rpc.Code_CODE_PERMISSION_DENIED: - errcode = errorcode.AccessDenied - case rpc.Code_CODE_NOT_FOUND: - errcode = errorcode.ItemNotFound - case rpc.Code_CODE_LOCKED: - errcode = errorcode.ItemIsLocked - case rpc.Code_CODE_INVALID_ARGUMENT: - errcode = errorcode.InvalidRequest - case rpc.Code_CODE_FAILED_PRECONDITION: - errcode = errorcode.InvalidRequest - default: - errcode = errorcode.GeneralException - } - return errcode -} diff --git a/tests/acceptance/expected-failures-localAPI-on-OCIS-storage.md b/tests/acceptance/expected-failures-localAPI-on-OCIS-storage.md index c4138df9255..0dc5ac6f89d 100644 --- a/tests/acceptance/expected-failures-localAPI-on-OCIS-storage.md +++ b/tests/acceptance/expected-failures-localAPI-on-OCIS-storage.md @@ -385,5 +385,20 @@ The expected failures in this file are from features in the owncloud/ocis repo. - [apiActivities/activities.feature:3875](https://github.com/owncloud/ocis/blob/master/tests/acceptance/features/apiActivities/activities.feature#L3875) +#### [The user role downgrading to Use Light disables the Personal space](https://github.com/owncloud/ocis/issues/11696) + +- [apiSettings/notificationSetting.feature:160](https://github.com/owncloud/ocis/blob/master/tests/acceptance/features/apiSettings/notificationSetting.feature#L160) +- [apiSettings/notificationSetting.feature:613](https://github.com/owncloud/ocis/blob/master/tests/acceptance/features/apiSettings/notificationSetting.feature#L613) +- [apiNotification/deprovisioningNotification.feature:100](https://github.com/owncloud/ocis/blob/master/tests/acceptance/features/apiNotification/deprovisioningNotification.feature#L100) +- [apiNotification/deprovisioningNotification.feature:171](https://github.com/owncloud/ocis/blob/master/tests/acceptance/features/apiNotification/deprovisioningNotification.feature#L171) +- [apiNotification/spaceNotification.feature:178](https://github.com/owncloud/ocis/blob/master/tests/acceptance/features/apiNotification/spaceNotification.feature#L178) +- [apiNotification/spaceNotification.feature:222](https://github.com/owncloud/ocis/blob/master/tests/acceptance/features/apiNotification/spaceNotification.feature#L222) +- [apiSpaces/changeSpaces.feature:529](https://github.com/owncloud/ocis/blob/master/tests/acceptance/features/apiSpaces/changeSpaces.feature#L529) +- [apiGraphUser/editUser.feature:227](https://github.com/owncloud/ocis/blob/master/tests/acceptance/features/apiGraphUser/editUser.feature#L227) +- [apiGraphUser/editUser.feature:231](https://github.com/owncloud/ocis/blob/master/tests/acceptance/features/apiGraphUser/editUser.feature#L231) +- [apiGraphUser/editUser.feature:235](https://github.com/owncloud/ocis/blob/master/tests/acceptance/features/apiGraphUser/editUser.feature#L235) +- [apiGraphUser/getUser.feature:696](https://github.com/owncloud/ocis/blob/master/tests/acceptance/features/apiGraphUser/getUser.feature#L696) +- [apiGraphUser/getUser.feature:700](https://github.com/owncloud/ocis/blob/master/tests/acceptance/features/apiGraphUser/getUser.feature#L700) + Note: always have an empty line at the end of this file. The bash script that processes this file requires that the last line has a newline on the end.