Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement space membership endpoints #2250

Merged
merged 3 commits into from
Dec 2, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions changelog/unreleased/space-membership.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
Enhancement: Implement space membership endpoints

Implemented endpoints to add and remove members to spaces.

https://github.com/owncloud/ocis/issues/2740
https://github.com/cs3org/reva/pull/2250
1 change: 1 addition & 0 deletions internal/http/services/owncloud/ocs/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ type Config struct {
Config data.ConfigData `mapstructure:"config"`
Capabilities data.CapabilitiesData `mapstructure:"capabilities"`
GatewaySvc string `mapstructure:"gatewaysvc"`
StorageregistrySvc string `mapstructure:"storage_registry_svc"`
DefaultUploadProtocol string `mapstructure:"default_upload_protocol"`
UserAgentChunkingMap map[string]string `mapstructure:"user_agent_chunking_map"`
SharePrefix string `mapstructure:"share_prefix"`
Expand Down
3 changes: 3 additions & 0 deletions internal/http/services/owncloud/ocs/conversions/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,9 @@ const (

// ShareTypeFederatedCloudShare represents a federated share
ShareTypeFederatedCloudShare ShareType = 6

// ShareTypeSpaceMembership represents an action regarding space members
ShareTypeSpaceMembership ShareType = 7
)

// ResourceType indicates the OCS type of the resource
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ import (
"strconv"

rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1"
collaboration "github.com/cs3org/go-cs3apis/cs3/sharing/collaboration/v1beta1"
link "github.com/cs3org/go-cs3apis/cs3/sharing/link/v1beta1"
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
types "github.com/cs3org/go-cs3apis/cs3/types/v1beta1"
Expand Down Expand Up @@ -206,32 +205,10 @@ func (h *Handler) isPublicShare(r *http.Request, oid string) bool {
})
if err != nil {
logger.Err(err)
}

if psRes.GetShare() != nil {
return true
}

// check if we have a user share
uRes, err := client.GetShare(r.Context(), &collaboration.GetShareRequest{
Ref: &collaboration.ShareReference{
Spec: &collaboration.ShareReference_Id{
Id: &collaboration.ShareId{
OpaqueId: oid,
},
},
},
})
if err != nil {
logger.Err(err)
}

if uRes.GetShare() != nil {
return false
}

// TODO token is neither a public or a user share.
return false
return psRes.GetShare() != nil
}

func (h *Handler) updatePublicShare(w http.ResponseWriter, r *http.Request, shareID string) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ const (
// Handler implements the shares part of the ownCloud sharing API
type Handler struct {
gatewayAddr string
storageRegistryAddr string
publicURL string
sharePrefix string
homeNamespace string
Expand All @@ -91,6 +92,7 @@ func getCacheWarmupManager(c *config.Config) (cache.Warmup, error) {
// Init initializes this and any contained handlers
func (h *Handler) Init(c *config.Config) {
h.gatewayAddr = c.GatewaySvc
h.storageRegistryAddr = c.StorageregistrySvc
h.publicURL = c.Config.Host
h.sharePrefix = c.SharePrefix
h.homeNamespace = c.HomeNamespace
Expand Down Expand Up @@ -122,6 +124,20 @@ func (h *Handler) startCacheWarmup(c cache.Warmup) {
}
}

func (h *Handler) extractReference(r *http.Request) (provider.Reference, error) {
var ref provider.Reference
if p := r.FormValue("path"); p != "" {
ref = provider.Reference{Path: path.Join(h.homeNamespace, p)}
} else if spaceRef := r.FormValue("space_ref"); spaceRef != "" {
var err error
ref, err = utils.ParseStorageSpaceReference(spaceRef)
if err != nil {
return provider.Reference{}, err
}
}
return ref, nil
}

// CreateShare handles POST requests on /apps/files_sharing/api/v1/shares
func (h *Handler) CreateShare(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
Expand All @@ -138,14 +154,17 @@ func (h *Handler) CreateShare(w http.ResponseWriter, r *http.Request) {
return
}

// prefix the path with the owners home, because ocs share requests are relative to the home dir
fn := path.Join(h.homeNamespace, r.FormValue("path"))
ref, err := h.extractReference(r)
if err != nil {
response.WriteOCSError(w, r, response.MetaBadRequest.StatusCode, "could not parse the reference", fmt.Errorf("could not parse the reference"))
return
}

statReq := provider.StatRequest{
Ref: &provider.Reference{Path: fn},
Ref: &ref,
}

sublog := appctx.GetLogger(ctx).With().Str("path", fn).Logger()
sublog := appctx.GetLogger(ctx).With().Interface("ref", ref).Logger()

statRes, err := client.Stat(ctx, &statReq)
if err != nil {
Expand Down Expand Up @@ -186,6 +205,16 @@ func (h *Handler) CreateShare(w http.ResponseWriter, r *http.Request) {
if role, val, err := h.extractPermissions(w, r, statRes.Info, conversions.NewViewerRole()); err == nil {
h.createFederatedCloudShare(w, r, statRes.Info, role, val)
}
case int(conversions.ShareTypeSpaceMembership):
if role, val, err := h.extractPermissions(w, r, statRes.Info, conversions.NewViewerRole()); err == nil {
switch role.Name {
case conversions.RoleManager, conversions.RoleEditor, conversions.RoleViewer:
h.addSpaceMember(w, r, statRes.Info, role, val)
default:
response.WriteOCSError(w, r, response.MetaBadRequest.StatusCode, "invalid role for space member", nil)
return
}
}
default:
response.WriteOCSError(w, r, response.MetaBadRequest.StatusCode, "unknown share type", nil)
}
Expand Down Expand Up @@ -478,11 +507,15 @@ func (h *Handler) updateShare(w http.ResponseWriter, r *http.Request, shareID st
// RemoveShare handles DELETE requests on /apps/files_sharing/api/v1/shares/(shareid)
func (h *Handler) RemoveShare(w http.ResponseWriter, r *http.Request) {
shareID := chi.URLParam(r, "shareid")
if h.isPublicShare(r, shareID) {
switch {
case h.isPublicShare(r, shareID):
h.removePublicShare(w, r, shareID)
return
case h.isUserShare(r, shareID):
h.removeUserShare(w, r, shareID)
default:
// The request is a remove space member request.
h.removeSpaceMember(w, r, shareID)
}
h.removeUserShare(w, r, shareID)
}

// ListShares handles GET requests on /apps/files_sharing/api/v1/shares
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,213 @@
// Copyright 2018-2021 CERN
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// In applying this license, CERN does not waive the privileges and immunities
// granted to it by virtue of its status as an Intergovernmental Organization
// or submit itself to any jurisdiction.

package shares

import (
"context"
"fmt"
"net/http"

groupv1beta1 "github.com/cs3org/go-cs3apis/cs3/identity/group/v1beta1"
userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1"
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
registry "github.com/cs3org/go-cs3apis/cs3/storage/registry/v1beta1"
"github.com/cs3org/reva/internal/http/services/owncloud/ocs/conversions"
"github.com/cs3org/reva/internal/http/services/owncloud/ocs/response"
"github.com/cs3org/reva/pkg/appctx"
"github.com/cs3org/reva/pkg/errtypes"
"github.com/cs3org/reva/pkg/rgrpc/status"
"github.com/cs3org/reva/pkg/rgrpc/todo/pool"
"github.com/cs3org/reva/pkg/utils"
"github.com/pkg/errors"
)

func (h *Handler) getGrantee(ctx context.Context, name string) (provider.Grantee, error) {
log := appctx.GetLogger(ctx)
client, err := pool.GetGatewayServiceClient(h.gatewayAddr)
if err != nil {
return provider.Grantee{}, err
}
userRes, err := client.GetUserByClaim(ctx, &userpb.GetUserByClaimRequest{
Claim: "username",
Value: name,
})
if err == nil && userRes.Status.Code == rpc.Code_CODE_OK {
return provider.Grantee{
Type: provider.GranteeType_GRANTEE_TYPE_USER,
Id: &provider.Grantee_UserId{UserId: userRes.User.Id},
}, nil
}
log.Debug().Str("name", name).Msg("no user found")

groupRes, err := client.GetGroupByClaim(ctx, &groupv1beta1.GetGroupByClaimRequest{
Claim: "group_name",
Value: name,
})
if err == nil && groupRes.Status.Code == rpc.Code_CODE_OK {
return provider.Grantee{
Type: provider.GranteeType_GRANTEE_TYPE_GROUP,
Id: &provider.Grantee_GroupId{GroupId: groupRes.Group.Id},
}, nil
}
log.Debug().Str("name", name).Msg("no group found")

return provider.Grantee{}, fmt.Errorf("no grantee found with name %s", name)
}

func (h *Handler) addSpaceMember(w http.ResponseWriter, r *http.Request, info *provider.ResourceInfo, role *conversions.Role, roleVal []byte) {
ctx := r.Context()

shareWith := r.FormValue("shareWith")
if shareWith == "" {
response.WriteOCSError(w, r, response.MetaBadRequest.StatusCode, "missing shareWith", nil)
return
}

grantee, err := h.getGrantee(ctx, shareWith)
if err != nil {
response.WriteOCSError(w, r, response.MetaNotFound.StatusCode, "error getting grantee", err)
return
}

ref := &provider.Reference{ResourceId: info.Id}

providers, err := h.findProviders(ctx, ref)
if err != nil {
response.WriteOCSError(w, r, response.MetaNotFound.StatusCode, "error getting storage provider", err)
return
}

providerClient, err := h.getStorageProviderClient(providers[0])
if err != nil {
response.WriteOCSError(w, r, response.MetaNotFound.StatusCode, "error getting storage provider", err)
return
}

addGrantRes, err := providerClient.AddGrant(ctx, &provider.AddGrantRequest{
Ref: ref,
Grant: &provider.Grant{
Grantee: &grantee,
Permissions: role.CS3ResourcePermissions(),
},
})
if err != nil || addGrantRes.Status.Code != rpc.Code_CODE_OK {
response.WriteOCSError(w, r, response.MetaServerError.StatusCode, "could not add space member", err)
return
}

response.WriteOCSSuccess(w, r, nil)
}

func (h *Handler) removeSpaceMember(w http.ResponseWriter, r *http.Request, spaceID string) {
ctx := r.Context()

shareWith := r.URL.Query().Get("shareWith")
if shareWith == "" {
response.WriteOCSError(w, r, response.MetaBadRequest.StatusCode, "missing shareWith", nil)
return
}

grantee, err := h.getGrantee(ctx, shareWith)
if err != nil {
response.WriteOCSError(w, r, response.MetaNotFound.StatusCode, "error getting grantee", err)
return
}

ref, err := utils.ParseStorageSpaceReference(spaceID)
if err != nil {
response.WriteOCSError(w, r, response.MetaBadRequest.StatusCode, "could not parse space id", err)
return
}

providers, err := h.findProviders(ctx, &ref)
if err != nil {
response.WriteOCSError(w, r, response.MetaNotFound.StatusCode, "error getting storage provider", err)
return
}

providerClient, err := h.getStorageProviderClient(providers[0])
if err != nil {
response.WriteOCSError(w, r, response.MetaNotFound.StatusCode, "error getting storage provider", err)
return
}

removeGrantRes, err := providerClient.RemoveGrant(ctx, &provider.RemoveGrantRequest{
Ref: &ref,
Grant: &provider.Grant{
Grantee: &grantee,
},
})
if err != nil {
response.WriteOCSError(w, r, response.MetaServerError.StatusCode, "error removing grant", err)
return
}
if removeGrantRes.Status.Code != rpc.Code_CODE_OK {
response.WriteOCSError(w, r, response.MetaServerError.StatusCode, "error removing grant", err)
return
}

response.WriteOCSSuccess(w, r, nil)
}

func (h *Handler) getStorageProviderClient(p *registry.ProviderInfo) (provider.ProviderAPIClient, error) {
c, err := pool.GetStorageProviderServiceClient(p.Address)
if err != nil {
err = errors.Wrap(err, "gateway: error getting a storage provider client")
return nil, err
}

return c, nil
}

func (h *Handler) findProviders(ctx context.Context, ref *provider.Reference) ([]*registry.ProviderInfo, error) {
c, err := pool.GetStorageRegistryClient(h.storageRegistryAddr)
if err != nil {
return nil, errors.Wrap(err, "gateway: error getting storage registry client")
}

res, err := c.GetStorageProviders(ctx, &registry.GetStorageProvidersRequest{
Ref: ref,
})

if err != nil {
return nil, errors.Wrap(err, "gateway: error calling GetStorageProvider")
}

if res.Status.Code != rpc.Code_CODE_OK {
switch res.Status.Code {
case rpc.Code_CODE_NOT_FOUND:
return nil, errtypes.NotFound("gateway: storage provider not found for reference:" + ref.String())
case rpc.Code_CODE_PERMISSION_DENIED:
return nil, errtypes.PermissionDenied("gateway: " + res.Status.Message + " for " + ref.String() + " with code " + res.Status.Code.String())
case rpc.Code_CODE_INVALID_ARGUMENT, rpc.Code_CODE_FAILED_PRECONDITION, rpc.Code_CODE_OUT_OF_RANGE:
return nil, errtypes.BadRequest("gateway: " + res.Status.Message + " for " + ref.String() + " with code " + res.Status.Code.String())
case rpc.Code_CODE_UNIMPLEMENTED:
return nil, errtypes.NotSupported("gateway: " + res.Status.Message + " for " + ref.String() + " with code " + res.Status.Code.String())
default:
return nil, status.NewErrorFromCode(res.Status.Code, "gateway")
}
}

if res.Providers == nil {
return nil, errtypes.NotFound("gateway: provider is nil")
}

return res.Providers, nil
}
Loading