added protected-* spaces get and create

This commit is contained in:
Roman Perekhod committed 2026-03-04 16:20:07 +01:00
1 parent 21310ea0e8
commit 34f38b8f66
7 files changed
+135 -26

No files matched your search

+1
View File
@@ -64,3 +64,4 @@ go.work.sum
.envrc
CLAUDE.md
.claude/
.agents/
@@ -160,6 +160,14 @@ func spacesProviders(cfg *config.Config, logger log.Logger) map[string]map[strin
"mount_point": "/projects",
"path_template": "/projects/{{.Space.Name}}",
},
"protected-personal": map[string]interface{}{
"mount_point": "/protected-users",
"path_template": "/protected-users/{{.Space.Owner.Id.OpaqueId}}",
},
"protected-project": map[string]interface{}{
"mount_point": "/protected-projects",
"path_template": "/protected-projects/{{.Space.Name}}",
},
},
},
cfg.StorageSharesEndpoint: {
+26 -22
View File
@@ -29,7 +29,6 @@ import (
"google.golang.org/protobuf/proto"
"github.com/owncloud/ocis/v2/ocis-pkg/l10n"
"github.com/owncloud/ocis/v2/ocis-pkg/mfa"
v0 "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"
@@ -37,11 +36,13 @@ import (
)
const (
_spaceTypePersonal = "personal"
_spaceTypeProject = "project"
_spaceTypeVirtual = "virtual"
_spaceTypeMountpoint = "mountpoint"
_spaceStateTrashed = "trashed"
_spaceTypePersonal = "personal"
_spaceTypeProject = "project"
_spaceTypeProtectedPersonal = "protected-personal"
_spaceTypeProtectedProject = "protected-project"
_spaceTypeVirtual = "virtual"
_spaceTypeMountpoint = "mountpoint"
_spaceStateTrashed = "trashed"
_sortDescending = "desc"
)
@@ -78,7 +79,7 @@ func (g Graph) GetDrives(version APIVersion) http.HandlerFunc {
// GetDrivesV1 attempts to retrieve the current users drives;
// it lists all drives the current user has access to.
func (g Graph) GetDrivesV1(w http.ResponseWriter, r *http.Request) {
spaces, errCode := g.getDrives(r, false, APIVersion_1)
spaces, errCode := g.getDrives(w, r, false, APIVersion_1)
if errCode != nil {
errorcode.RenderError(w, r, errCode)
return
@@ -99,7 +100,7 @@ func (g Graph) GetDrivesV1(w http.ResponseWriter, r *http.Request) {
// it includes the grantedtoV2 property
// it uses unified roles instead of the cs3 representations
func (g Graph) GetDrivesV1Beta1(w http.ResponseWriter, r *http.Request) {
spaces, errCode := g.getDrives(r, false, APIVersion_1_Beta_1)
spaces, errCode := g.getDrives(w, r, false, APIVersion_1_Beta_1)
if errCode != nil {
errorcode.RenderError(w, r, errCode)
return
@@ -133,14 +134,11 @@ func (g Graph) GetAllDrives(version APIVersion) http.HandlerFunc {
// GetAllDrivesV1 attempts to retrieve the current users drives;
// it includes another user's drives, if the current user has the permission.
func (g Graph) GetAllDrivesV1(w http.ResponseWriter, r *http.Request) {
if !mfa.Has(r.Context()) {
logger := g.logger.SubloggerWithRequestID(r.Context())
logger.Error().Str("path", r.URL.Path).Msg("MFA required but not satisfied")
mfa.SetRequiredStatus(w)
if !g.validateMFA(r, w) {
return
}
spaces, errCode := g.getDrives(r, true, APIVersion_1)
spaces, errCode := g.getDrives(w, r, true, APIVersion_1)
if errCode != nil {
errorcode.RenderError(w, r, errCode)
return
@@ -160,14 +158,11 @@ func (g Graph) GetAllDrivesV1(w http.ResponseWriter, r *http.Request) {
// it includes the grantedtoV2 property
// it uses unified roles instead of the cs3 representations
func (g Graph) GetAllDrivesV1Beta1(w http.ResponseWriter, r *http.Request) {
if !mfa.Has(r.Context()) {
logger := g.logger.SubloggerWithRequestID(r.Context())
logger.Error().Str("path", r.URL.Path).Msg("MFA required but not satisfied")
mfa.SetRequiredStatus(w)
if !g.validateMFA(r, w) {
return
}
drives, errCode := g.getDrives(r, true, APIVersion_1_Beta_1)
drives, errCode := g.getDrives(w, r, true, APIVersion_1_Beta_1)
if errCode != nil {
errorcode.RenderError(w, r, errCode)
return
@@ -184,7 +179,7 @@ func (g Graph) GetAllDrivesV1Beta1(w http.ResponseWriter, r *http.Request) {
}
// getDrives implements the Service interface.
func (g Graph) getDrives(r *http.Request, unrestricted bool, apiVersion APIVersion) ([]*libregraph.Drive, error) {
func (g Graph) getDrives(w http.ResponseWriter, r *http.Request, unrestricted bool, apiVersion APIVersion) ([]*libregraph.Drive, error) {
logger := g.logger.SubloggerWithRequestID(r.Context())
logger.Info().
Interface("query", r.URL.Query()).
@@ -197,6 +192,10 @@ func (g Graph) getDrives(r *http.Request, unrestricted bool, apiVersion APIVersi
logger.Debug().Err(err).Interface("query", r.URL.Query()).Msg("could not get drives: query error")
return nil, errorcode.New(errorcode.InvalidRequest, err.Error())
}
if !g.validateQueryMFA(r, w, odataReq.Query, DriveTypeValidator{}) {
return nil, errorcode.New(errorcode.AccessDenied, "")
}
ctx := r.Context()
filters, err := generateCs3Filters(odataReq)
@@ -409,6 +408,8 @@ func (g Graph) createDrive(w http.ResponseWriter, r *http.Request, apiVersion AP
switch driveType {
case "", _spaceTypeProject:
driveType = _spaceTypeProject
case _spaceTypeProtectedProject:
driveType = _spaceTypeProtectedProject
default:
logger.Debug().Str("type", driveType).Msg("could not create drive: drives of this type cannot be created via this api")
errorcode.InvalidRequest.Render(w, r, http.StatusBadRequest, "drives of this type cannot be created via this api")
@@ -468,7 +469,7 @@ func (g Graph) createDrive(w http.ResponseWriter, r *http.Request, apiVersion AP
}
space := resp.GetStorageSpace()
if t := r.URL.Query().Get(TemplateParameter); t != "" && driveType == _spaceTypeProject {
if t := r.URL.Query().Get(TemplateParameter); t != "" && (driveType == _spaceTypeProject || driveType == _spaceTypeProtectedProject) {
loc := l10n.MustGetUserLocale(ctx, us.GetId().GetOpaqueId(), r.Header.Get(HeaderAcceptLanguage), g.valueService)
if err := g.applySpaceTemplate(ctx, gatewayClient, space.GetRoot(), t, loc); err != nil {
logger.Error().Err(err).Msg("could not apply template to space")
@@ -596,7 +597,7 @@ func (g Graph) updateDrive(w http.ResponseWriter, r *http.Request, apiVersion AP
for _, sp := range res.StorageSpaces {
id, _ := storagespace.ParseID(sp.GetId().GetOpaqueId())
if id.GetSpaceId() == rid.GetSpaceId() {
dt = _spaceTypeProject
dt = sp.SpaceType
}
}
}
@@ -1016,9 +1017,12 @@ func getQuota(quota *libregraph.Quota, defaultQuota string) *storageprovider.Quo
func (g Graph) canSetSpaceQuota(ctx context.Context, _ *userv1beta1.User, typ string) (bool, error) {
permID := settingsServiceExt.SetPersonalSpaceQuotaPermission(0).Id
if typ == _spaceTypeProject {
if typ == _spaceTypeProject || typ == _spaceTypeProtectedProject {
permID = settingsServiceExt.SetProjectSpaceQuotaPermission(0).Id
}
if typ == _spaceTypeProtectedPersonal {
permID = settingsServiceExt.SetPersonalSpaceQuotaPermission(0).Id
}
_, err := g.permissionsService.GetPermissionByID(ctx, &settingssvc.GetPermissionByIDRequest{PermissionId: permID})
if err != nil {
merror := merrors.FromError(err)
+50
View File
@@ -214,6 +214,25 @@ func (v BasicQueryValidator) Validate(query *godata.GoDataQuery) error {
return nil
}
// DriveTypeValidator validates if the driveType filter contains protected types.
type DriveTypeValidator struct{}
// Validate checks if the driveType filter contains protected types.
func (v DriveTypeValidator) Validate(query *godata.GoDataQuery) error {
if query == nil || query.Filter == nil {
return nil
}
if query.Filter.Tree.Token.Value == "eq" && query.Filter.Tree.Children[0].Token.Value == "driveType" {
driveType := strings.Trim(query.Filter.Tree.Children[1].Token.Value, "'")
if strings.HasPrefix(driveType, "protected-") {
return errors.New("mfa required for protected spaces")
}
}
return nil
}
// validateQuery validates the godata query based on provided validators.
// It handles user permissions and MFA requirements centrally.
func (g Graph) validateQuery(r *http.Request, w http.ResponseWriter, query *godata.GoDataQuery, validators ...QueryValidator) bool {
@@ -237,3 +256,34 @@ func (g Graph) validateQuery(r *http.Request, w http.ResponseWriter, query *goda
}
return true
}
// validateQueryMFA validates the godata query based on provided validators.
// It only handles MFA requirements and does not check for user permissions.
func (g Graph) validateQueryMFA(r *http.Request, w http.ResponseWriter, query *godata.GoDataQuery, validators ...QueryValidator) bool {
hasMFA := mfa.Has(r.Context())
logger := g.logger.SubloggerWithRequestID(r.Context())
for _, v := range validators {
if err := v.Validate(query); err != nil {
if !hasMFA {
logger.Error().Str("path", r.URL.Path).Msg("MFA required but not satisfied")
mfa.SetRequiredStatus(w)
return false
}
}
}
return true
}
// validateMFA validates the MFA requirement.
func (g Graph) validateMFA(r *http.Request, w http.ResponseWriter) bool {
hasMFA := mfa.Has(r.Context())
logger := g.logger.SubloggerWithRequestID(r.Context())
if !hasMFA {
logger.Error().Str("path", r.URL.Path).Msg("MFA required but not satisfied")
mfa.SetRequiredStatus(w)
return false
}
return true
}
@@ -811,6 +811,53 @@ var _ = Describe("Graph", func() {
Expect(*response.DriveAlias).To(Equal("project/testspace"))
Expect(*response.Description).To(Equal("This space is for testing"))
})
It("can create a protected-project space", func() {
gatewayClient.On("CreateStorageSpace", mock.Anything, mock.Anything).Return(&provider.CreateStorageSpaceResponse{
Status: status.NewOK(ctx),
StorageSpace: &provider.StorageSpace{
Id: &provider.StorageSpaceId{OpaqueId: "newID"},
Name: "Top Secret Project",
SpaceType: "protected-project",
Root: &provider.ResourceId{
StorageId: "pro-1",
SpaceId: "newID",
OpaqueId: "newID",
},
Opaque: &typesv1beta1.Opaque{
Map: map[string]*typesv1beta1.OpaqueEntry{
"description": {Decoder: "plain", Value: []byte("This space is protected")},
"spaceAlias": {Decoder: "plain", Value: []byte("protected-project/topsecretproject")},
},
},
},
}, nil)
permissionService.On("GetPermissionByID", mock.Anything, mock.Anything).Return(&settingssvc.GetPermissionByIDResponse{
Permission: &v0.Permission{
Operation: v0.Permission_OPERATION_READWRITE,
Constraint: v0.Permission_CONSTRAINT_ALL,
},
}, nil)
gatewayClient.On("GetQuota", mock.Anything, mock.Anything).Return(&provider.GetQuotaResponse{
Status: status.NewOK(ctx),
TotalBytes: 500,
}, nil)
jsonBody := []byte(`{"name": "Top Secret Project", "driveType": "protected-project", "description": "This space is protected"}`)
r := httptest.NewRequest(http.MethodPost, "/graph/v1.0/drives", bytes.NewBuffer(jsonBody)).WithContext(ctx)
rr := httptest.NewRecorder()
svc.CreateDrive(rr, r)
Expect(rr.Code).To(Equal(http.StatusCreated))
body, _ := io.ReadAll(rr.Body)
var response libregraph.Drive
err := json.Unmarshal(body, &response)
Expect(err).ToNot(HaveOccurred())
Expect(response.Name).To(Equal("Top Secret Project"))
Expect(*response.DriveType).To(Equal("protected-project"))
Expect(*response.Description).To(Equal("This space is protected"))
})
It("Incomplete space", func() {
gatewayClient.On("CreateStorageSpace", mock.Anything, mock.Anything).Return(&provider.CreateStorageSpaceResponse{
Status: status.NewOK(ctx),
+1 -2
View File
@@ -31,7 +31,6 @@ func (g Graph) GetGroups(w http.ResponseWriter, r *http.Request) {
errorcode.InvalidRequest.Render(w, r, http.StatusBadRequest, err.Error())
return
}
ctxHasFullPerms := g.contextUserHasFullAccountPerms(r.Context())
if !g.validateQuery(r, w, odataReq.Query, SearchValidator{MinLength: g.config.API.IdentitySearchMinLength}, BasicQueryValidator{}) {
return
@@ -44,7 +43,7 @@ func (g Graph) GetGroups(w http.ResponseWriter, r *http.Request) {
return
}
// If the user isn't admin, we'll show just the minimum group attibutes
if !ctxHasFullPerms {
if !g.contextUserHasFullAccountPerms(r.Context()) {
finalGroups := make([]*libregraph.Group, len(groups))
for i, grp := range groups {
finalGroups[i] = &libregraph.Group{
+2 -2
View File
@@ -323,8 +323,6 @@ func (g Graph) GetUsers(w http.ResponseWriter, r *http.Request) {
return
}
ctxHasFullPerms := g.contextUserHasFullAccountPerms(r.Context())
if !g.validateQuery(r, w, odataReq.Query, SearchValidator{MinLength: g.config.API.IdentitySearchMinLength}, FilterValidator{}, BasicQueryValidator{}) {
return
}
@@ -393,6 +391,8 @@ func (g Graph) GetUsers(w http.ResponseWriter, r *http.Request) {
usersWithAttributes := make([]*UserWithAttributes, 0, len(users))
displayedAttributes := g.config.API.UserSearchDisplayedAttributes
ctxHasFullPerms := g.contextUserHasFullAccountPerms(r.Context())
for _, user := range users {
attributes, err := getUsersAttributes(displayedAttributes, user)
if err != nil {