Compare commits

...
Author SHA1 Message Date
Matteo cd9821abe6 feat(web): [OCISDEV-1516] warn about group members without vault access when sharing
Show a notice in the share form when a group is selected for a vault resource, and add the same information to the "Share with people" help.

Signed-off-by: Matteo <matteo.sonnenholzner@kiteworks.com>
2026-10-29 13:55:17 +01:00
Roman PerekhodandClaude Opus 5.5 b5cc5cc415 refactor: [OCISDEV-1516] share the vault recipient filter
- Move the VaultMode recipient filter to ocis-pkg/vault as
  FilterVaultModeUsers. The notifications and userlog services both use
  it.
- Run the checks in parallel, with at most 10 at the same time, so that
  a large group does not block the event handler.
- Add a tracing span with the number of checked, allowed and failed
  users.
- In the notifications service, check the vault permission before the
  settings and user lookups, so that a member without the permission
  costs one call only.
- Log a failed check with the user ID only, without the "event" field.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 13:55:17 +01:00
Roman PerekhodandClaude Opus 5.5 f7790d7be5 test: [OCISDEV-1516] check vault notifications and access for group members
- Add a scenario outline for a vault resource share to a group: only the
  group members with the VaultMode permission get an in-app
  notification and can download the file. The other members get no
  notification, cannot download the file, and do not see it in the
  Shares space.
- Add a scenario outline for a vault space membership of a group, with
  the space roles Manager, Space Viewer and Space Editor. Only the group
  members with the VaultMode permission get the notification and can
  access the space. The other members cannot download the file and do
  not see the space in their drive list.
- The examples cover the roles Space Admin, Admin, User Light and User.
- Assign the role "Space Admin" to Brian in the group share scenario,
  because the default role has no VaultMode permission.
- Add NotificationContext to the apiVault suite.
- Fix the pull request number in the changelog.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 13:55:17 +01:00
Roman PerekhodandClaude Opus 5.5 f456f905c8 feat: [OCISDEV-1516] allow group shares in the vault
- web: the share dialog searches for groups in vault mode.
- notifications, userlog: send vault notifications only to the users
  who hold the VaultMode permission. A group can contain other users.
- ocis-pkg/vault: add the shared helpers for the vault checks.
- acceptance: a group invitation to a vault resource now succeeds.

The gateway change is in owncloud/reva#787.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 13:55:13 +01:00
24 changed files with 935 additions and 66 deletions

No files matched your search

@@ -0,0 +1,11 @@
Enhancement: Allow group shares in the vault
Users can now invite a group to a resource in the vault (Safe). Before this
change, the server accepted only users as vault share recipients. The share
dialog in Web now also searches for groups in vault mode. The
notifications and userlog services now send a vault notification only to the
group members who have the permission to use the vault. The other group
members get no email and no in-app notification.
https://github.com/owncloud/ocis/pull/13260
https://github.com/owncloud/reva/pull/787
+1 -1
View File
@@ -67,7 +67,7 @@ require (
github.com/open-policy-agent/opa v1.21.1
github.com/orcaman/concurrent-map v1.0.0
github.com/owncloud/libre-graph-api-go v1.0.5-0.20260216101009-eeac018af245
github.com/owncloud/reva/v2 v2.0.0-20261022133635-764ed1d17629
github.com/owncloud/reva/v2 v2.0.0-20261028142447-7ce5132a4574
github.com/pkg/errors v0.9.1
github.com/pkg/xattr v0.4.12
github.com/prometheus/client_golang v1.25.0
+2 -4
View File
@@ -736,10 +736,8 @@ github.com/orcaman/concurrent-map v1.0.0 h1:I/2A2XPCb4IuQWcQhBhSwGfiuybl/J0ev9HD
github.com/orcaman/concurrent-map v1.0.0/go.mod h1:Lu3tH6HLW3feq74c2GC+jIMS/K2CFcDWnWD9XkenwhI=
github.com/owncloud/libre-graph-api-go v1.0.5-0.20260216101009-eeac018af245 h1:JRidLTAKhnvyLMRtVtSF4lhBa0NSAOs6fof+d6JnKII=
github.com/owncloud/libre-graph-api-go v1.0.5-0.20260216101009-eeac018af245/go.mod h1:z61VMGAJRtR1nbgXWiNoCkxUXP1B3Je9rMuJbnGd+Og=
github.com/owncloud/reva/v2 v2.0.0-20261019155447-90c24c1b3575 h1:GOsblJHW/dvNdxxXmCb/PZOGRIg1ci4SVs+pA7hw6t4=
github.com/owncloud/reva/v2 v2.0.0-20261019155447-90c24c1b3575/go.mod h1:cgqg+UTe4ekjMbJj8hgoXSTxQ9fQramKcOUdvsFUrzc=
github.com/owncloud/reva/v2 v2.0.0-20261022133635-764ed1d17629 h1:h0jekinxPFEwKl0IkGT8iYOca9ZdIXJDixIIFI/yhfY=
github.com/owncloud/reva/v2 v2.0.0-20261022133635-764ed1d17629/go.mod h1:cgqg+UTe4ekjMbJj8hgoXSTxQ9fQramKcOUdvsFUrzc=
github.com/owncloud/reva/v2 v2.0.0-20261028142447-7ce5132a4574 h1:BDRlgU05VSMDzQC/7RWKtLHT8VcGxbQ9z0v7ycHQcEI=
github.com/owncloud/reva/v2 v2.0.0-20261028142447-7ce5132a4574/go.mod h1:cgqg+UTe4ekjMbJj8hgoXSTxQ9fQramKcOUdvsFUrzc=
github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c h1:rp5dCmg/yLR3mgFuSOe4oEnDDmGLROTvMragMUXpTQw=
github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c/go.mod h1:X07ZCGwUbLaax7L0S3Tw4hpejzu63ZrrQiUe6W0hcy0=
github.com/pablodz/inotifywaitgo v0.0.12 h1:DVJJTFMDlSAdO46yisPF2vzozs/r+4k6ih8MVghq78M=
+103
View File
@@ -0,0 +1,103 @@
// Package vault provides helpers for resources in the vault storage provider.
package vault
import (
"context"
"fmt"
gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1"
user "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
permissions "github.com/cs3org/go-cs3apis/cs3/permissions/v1beta1"
rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1"
"github.com/owncloud/reva/v2/pkg/permission"
"github.com/owncloud/reva/v2/pkg/storagespace"
"github.com/owncloud/reva/v2/pkg/utils"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
"golang.org/x/sync/errgroup"
)
// maxConcurrentChecks bounds how many VaultMode checks run at the same time, so that a large
// group does not send all its checks to the gateway at once.
const maxConcurrentChecks = 10
const tracerName = "github.com/owncloud/ocis/v2/ocis-pkg/vault"
// IsVaultStorage reports whether the storage ID belongs to the vault storage provider.
func IsVaultStorage(storageID string) bool {
return storageID == utils.VaultStorageProviderID
}
// IsVaultSpace reports whether the space ID belongs to the vault storage provider.
// It returns true for a space ID that it cannot parse, so that callers fail closed.
func IsVaultSpace(spaceID string) bool {
rid, err := storagespace.ParseID(spaceID)
if err != nil {
return true
}
return IsVaultStorage(rid.GetStorageId())
}
// HasVaultMode reports whether the user holds the VaultMode permission.
// A non-nil error means undetermined, so callers must treat the user as not allowed.
func HasVaultMode(ctx context.Context, gwc gateway.GatewayAPIClient, userID *user.UserId) (bool, error) {
res, err := gwc.CheckPermission(ctx, &permissions.CheckPermissionRequest{
SubjectRef: &permissions.SubjectReference{
Spec: &permissions.SubjectReference_UserId{UserId: userID},
},
Permission: permission.VaultMode,
})
if err != nil {
return false, err
}
switch code := res.GetStatus().GetCode(); code {
case rpc.Code_CODE_OK:
return true, nil
case rpc.Code_CODE_PERMISSION_DENIED:
return false, nil
default:
return false, fmt.Errorf("vault permission check returned status %q: %s", code, res.GetStatus().GetMessage())
}
}
// FilterVaultModeUsers returns the users from userIDs who hold the VaultMode permission, in the
// same order. A group can contain users without the permission, because the gateway does not
// check the group members. The checks run in parallel, with a bound. When a check fails, the
// function calls onError for that user and leaves the user out, so that the caller fails closed.
func FilterVaultModeUsers(ctx context.Context, gwc gateway.GatewayAPIClient, userIDs []*user.UserId, onError func(*user.UserId, error)) []*user.UserId {
ctx, span := trace.SpanFromContext(ctx).TracerProvider().Tracer(tracerName).Start(ctx, "FilterVaultModeUsers")
defer span.End()
span.SetAttributes(attribute.Int("vault.users.checked", len(userIDs)))
allowed := make([]bool, len(userIDs))
errs := make([]error, len(userIDs))
var eg errgroup.Group
eg.SetLimit(maxConcurrentChecks)
for i, id := range userIDs {
eg.Go(func() error {
allowed[i], errs[i] = HasVaultMode(ctx, gwc, id)
return nil
})
}
_ = eg.Wait()
filtered := make([]*user.UserId, 0, len(userIDs))
failed := 0
for i, id := range userIDs {
if errs[i] != nil {
failed++
if onError != nil {
onError(id, errs[i])
}
continue
}
if allowed[i] {
filtered = append(filtered, id)
}
}
span.SetAttributes(
attribute.Int("vault.users.allowed", len(filtered)),
attribute.Int("vault.users.failed", failed),
)
return filtered
}
+110
View File
@@ -0,0 +1,110 @@
package vault
import (
"context"
"errors"
"fmt"
"slices"
"testing"
user "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
permissions "github.com/cs3org/go-cs3apis/cs3/permissions/v1beta1"
rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1"
"github.com/owncloud/reva/v2/pkg/permission"
"github.com/owncloud/reva/v2/pkg/utils"
cs3mocks "github.com/owncloud/reva/v2/tests/cs3mocks/mocks"
"github.com/stretchr/testify/mock"
"google.golang.org/grpc"
)
func TestIsVaultSpace(t *testing.T) {
tests := []struct {
name string
spaceID string
want bool
}{
{"vault space", utils.VaultStorageProviderID + "$space-id", true},
{"regular space", "storage-id$space-id", false},
{"unparsable space id fails closed", "", true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := IsVaultSpace(tt.spaceID); got != tt.want {
t.Errorf("IsVaultSpace(%q) = %v, want %v", tt.spaceID, got, tt.want)
}
})
}
}
func TestHasVaultMode(t *testing.T) {
tests := []struct {
name string
res *permissions.CheckPermissionResponse
err error
want bool
wantErr bool
}{
{"ok grants", &permissions.CheckPermissionResponse{Status: &rpc.Status{Code: rpc.Code_CODE_OK}}, nil, true, false},
{"permission denied denies", &permissions.CheckPermissionResponse{Status: &rpc.Status{Code: rpc.Code_CODE_PERMISSION_DENIED}}, nil, false, false},
{"internal status fails closed", &permissions.CheckPermissionResponse{Status: &rpc.Status{Code: rpc.Code_CODE_INTERNAL}}, nil, false, true},
{"transport error fails closed", nil, errors.New("unavailable"), false, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gwc := &cs3mocks.GatewayAPIClient{}
gwc.On("CheckPermission", mock.Anything, mock.MatchedBy(func(req *permissions.CheckPermissionRequest) bool {
return req.GetPermission() == permission.VaultMode && req.GetSubjectRef().GetUserId().GetOpaqueId() == "alice"
})).Return(tt.res, tt.err)
got, err := HasVaultMode(context.Background(), gwc, &user.UserId{OpaqueId: "alice"})
if (err != nil) != tt.wantErr {
t.Fatalf("HasVaultMode() error = %v, wantErr %v", err, tt.wantErr)
}
if got != tt.want {
t.Errorf("HasVaultMode() = %v, want %v", got, tt.want)
}
gwc.AssertExpectations(t)
})
}
}
func TestFilterVaultModeUsers(t *testing.T) {
// alice and every "ok-" user hold the permission, bob does not, and the check for carol fails
gwc := &cs3mocks.GatewayAPIClient{}
gwc.On("CheckPermission", mock.Anything, mock.Anything).Return(func(_ context.Context, r *permissions.CheckPermissionRequest, _ ...grpc.CallOption) (*permissions.CheckPermissionResponse, error) {
switch id := r.GetSubjectRef().GetUserId().GetOpaqueId(); {
case id == "carol":
return nil, errors.New("unavailable")
case id == "bob":
return &permissions.CheckPermissionResponse{Status: &rpc.Status{Code: rpc.Code_CODE_PERMISSION_DENIED}}, nil
default:
return &permissions.CheckPermissionResponse{Status: &rpc.Status{Code: rpc.Code_CODE_OK}}, nil
}
})
ids := []*user.UserId{{OpaqueId: "alice"}, {OpaqueId: "bob"}, {OpaqueId: "carol"}}
for i := range 50 {
ids = append(ids, &user.UserId{OpaqueId: fmt.Sprintf("ok-%02d", i)})
}
var failed []string
got := FilterVaultModeUsers(context.Background(), gwc, ids, func(id *user.UserId, err error) {
failed = append(failed, id.GetOpaqueId())
})
want := []string{"alice"}
for i := range 50 {
want = append(want, fmt.Sprintf("ok-%02d", i))
}
gotIDs := make([]string, 0, len(got))
for _, id := range got {
gotIDs = append(gotIDs, id.GetOpaqueId())
}
if !slices.Equal(gotIDs, want) {
t.Errorf("FilterVaultModeUsers() = %v, want %v", gotIDs, want)
}
if !slices.Equal(failed, []string{"carol"}) {
t.Errorf("onError called for %v, want [carol]", failed)
}
gwc.AssertNumberOfCalls(t, "CheckPermission", len(ids))
}
+32 -4
View File
@@ -26,6 +26,7 @@ import (
"github.com/owncloud/ocis/v2/ocis-pkg/l10n"
"github.com/owncloud/ocis/v2/ocis-pkg/log"
"github.com/owncloud/ocis/v2/ocis-pkg/middleware"
"github.com/owncloud/ocis/v2/ocis-pkg/vault"
settingssvc "github.com/owncloud/ocis/v2/protogen/gen/ocis/services/settings/v0"
"github.com/owncloud/ocis/v2/services/notifications/pkg/channels"
"github.com/owncloud/ocis/v2/services/notifications/pkg/email"
@@ -196,8 +197,10 @@ func (s eventsNotifier) send(ctx context.Context, emails []*channels.Message) {
}
}
func (s eventsNotifier) ensureGranteeList(ctx context.Context, executant, u *user.UserId, g *group.GroupId) []*user.User {
granteeList, err := s.getGranteeList(ctx, executant, u, g)
// ensureGranteeList resolves the grantee to the users who get the notification.
// For a vault resource it keeps only the users who hold the VaultMode permission.
func (s eventsNotifier) ensureGranteeList(ctx context.Context, executant, u *user.UserId, g *group.GroupId, inVault bool) []*user.User {
granteeList, err := s.getGranteeList(ctx, executant, u, g, inVault)
if err != nil {
s.logger.Error().Err(err).Str("event", "ensureGranteeList").Msg("Could not get grantee list")
return nil
@@ -207,9 +210,18 @@ func (s eventsNotifier) ensureGranteeList(ctx context.Context, executant, u *use
return granteeList
}
func (s eventsNotifier) getGranteeList(ctx context.Context, executant, u *user.UserId, g *group.GroupId) ([]*user.User, error) {
func (s eventsNotifier) getGranteeList(ctx context.Context, executant, u *user.UserId, g *group.GroupId, inVault bool) ([]*user.User, error) {
switch {
case u != nil:
if inVault {
gatewayClient, err := s.gatewaySelector.Next()
if err != nil {
return nil, err
}
if len(s.filterVaultModeUsers(ctx, gatewayClient, []*user.UserId{u})) == 0 {
return nil, nil
}
}
if s.disableEmails(ctx, u) {
return nil, nil
}
@@ -236,12 +248,21 @@ func (s eventsNotifier) getGranteeList(ctx context.Context, executant, u *user.U
return nil, errors.New("could not get group")
}
userList := make([]*user.User, 0, len(res.GetGroup().GetMembers()))
members := make([]*user.UserId, 0, len(res.GetGroup().GetMembers()))
for _, userID := range res.GetGroup().GetMembers() {
// don't add the executant
if userID.GetOpaqueId() == executant.GetOpaqueId() {
continue
}
members = append(members, userID)
}
// check the vault permission first, so that members without it cost no further calls
if inVault {
members = s.filterVaultModeUsers(ctx, gatewayClient, members)
}
userList := make([]*user.User, 0, len(members))
for _, userID := range members {
// don't add users who opted out
if s.disableEmails(ctx, userID) {
continue
@@ -262,6 +283,13 @@ func (s eventsNotifier) getGranteeList(ctx context.Context, executant, u *user.U
}
}
// filterVaultModeUsers keeps only the users who hold the VaultMode permission.
func (s eventsNotifier) filterVaultModeUsers(ctx context.Context, gatewayClient gateway.GatewayAPIClient, userIDs []*user.UserId) []*user.UserId {
return vault.FilterVaultModeUsers(ctx, gatewayClient, userIDs, func(id *user.UserId, err error) {
s.logger.Error().Err(err).Str("userId", id.GetOpaqueId()).Msg("could not check the vault permission, user skipped")
})
}
func (s eventsNotifier) getUser(ctx context.Context, u *user.UserId) (*user.User, error) {
if u == nil {
return nil, errors.New("need at least one non-nil grantee")
@@ -24,6 +24,7 @@ import (
gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1"
user "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
permissions "github.com/cs3org/go-cs3apis/cs3/permissions/v1beta1"
rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1"
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
. "github.com/onsi/ginkgo/v2"
@@ -292,6 +293,7 @@ https://owncloud.com
DescribeTable("Vault resources are redacted in notifications",
func(ev events.Event, mustNotContain string) {
gatewayClient.On("CheckPermission", mock.Anything, mock.Anything).Return(&permissions.CheckPermissionResponse{Status: &rpc.Status{Code: rpc.Code_CODE_OK}}, nil)
received := make(chan *channels.Message, 1)
ch := make(chan events.Event)
evts := NewEventsNotifier(trace.NewNoopTracerProvider(), ch, capturingChannel{out: received}, log.NewLogger(), gatewaySelector, vs, "",
@@ -365,6 +367,66 @@ https://owncloud.com
},
}, "vault space"),
)
DescribeTable("Vault group grantees are filtered by the vault mode permission",
func(ev events.Event) {
outsider := &user.User{
Id: &user.UserId{OpaqueId: "outsider"},
Mail: "outsider@owncloud.com",
DisplayName: "Otto Outsider",
}
gatewayClient.On("GetGroup", mock.Anything, mock.Anything).Return(&group.GetGroupResponse{
Status: &rpc.Status{Code: rpc.Code_CODE_OK},
Group: &group.Group{Members: []*user.UserId{sharee.GetId(), outsider.GetId()}},
}, nil)
gatewayClient.On("GetUser", mock.Anything, mock.MatchedBy(func(r *user.GetUserRequest) bool {
return r.GetUserId().GetOpaqueId() == outsider.GetId().GetOpaqueId()
})).Return(&user.GetUserResponse{Status: &rpc.Status{Code: rpc.Code_CODE_OK}, User: outsider}, nil)
gatewayClient.On("CheckPermission", mock.Anything, mock.Anything).Return(func(_ context.Context, r *permissions.CheckPermissionRequest, _ ...grpc.CallOption) (*permissions.CheckPermissionResponse, error) {
code := rpc.Code_CODE_PERMISSION_DENIED
if r.GetSubjectRef().GetUserId().GetOpaqueId() == sharee.GetId().GetOpaqueId() {
code = rpc.Code_CODE_OK
}
return &permissions.CheckPermissionResponse{Status: &rpc.Status{Code: code}}, nil
})
received := make(chan *channels.Message, 2)
ch := make(chan events.Event)
evts := NewEventsNotifier(trace.NewNoopTracerProvider(), ch, capturingChannel{out: received}, log.NewLogger(), gatewaySelector, vs, "",
"", "", "", "", "", "",
store.Create(), nil, nil)
go evts.Run()
ch <- ev
var msg *channels.Message
select {
case msg = <-received:
case <-time.Tick(3 * time.Second):
Fail("timeout waiting for notification")
}
Expect(msg.Recipient).To(Equal([]string{sharee.GetMail()}))
Consistently(received, 200*time.Millisecond).ShouldNot(Receive())
},
Entry("Share Created", events.Event{
Event: events.ShareCreated{
Sharer: sharer.GetId(),
GranteeGroupID: &group.GroupId{OpaqueId: "vaultgroup"},
CTime: utils.TimeToTS(time.Date(2023, 4, 17, 16, 42, 0, 0, time.UTC)),
ItemID: vaultResourceID,
},
}),
Entry("Added to Space", events.Event{
Event: events.SpaceShared{
Executant: sharer.GetId(),
Creator: sharer.GetId(),
GranteeGroupID: &group.GroupId{OpaqueId: "vaultgroup"},
ID: vaultSpaceID,
},
}),
)
})
var _ = Describe("Notifications X-Site Scripting", func() {
+4 -3
View File
@@ -4,6 +4,7 @@ import (
"context"
user "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
"github.com/owncloud/ocis/v2/ocis-pkg/vault"
"github.com/owncloud/ocis/v2/services/notifications/pkg/email"
"github.com/owncloud/ocis/v2/services/settings/pkg/store/defaults"
"github.com/owncloud/reva/v2/pkg/events"
@@ -33,7 +34,7 @@ func (s eventsNotifier) handleShareCreated(baseCtx context.Context, e events.Sha
return
}
granteeList := s.ensureGranteeList(ctx, owner.GetId(), e.GranteeUserID, e.GranteeGroupID)
granteeList := s.ensureGranteeList(ctx, owner.GetId(), e.GranteeUserID, e.GranteeGroupID, vault.IsVaultStorage(e.ItemID.GetStorageId()))
filteredGrantees := s.filter.execute(ctx, granteeList, defaults.SettingUUIDProfileEventShareCreated)
recipientsInstant, recipientsDaily, recipientsInstantWeekly := s.splitter.execute(ctx, filteredGrantees)
@@ -123,7 +124,7 @@ func (s eventsNotifier) handleShareExpired(baseCtx context.Context, e events.Sha
return
}
granteeList := s.ensureGranteeList(ctx, owner.GetId(), e.GranteeUserID, e.GranteeGroupID)
granteeList := s.ensureGranteeList(ctx, owner.GetId(), e.GranteeUserID, e.GranteeGroupID, vault.IsVaultStorage(e.ItemID.GetStorageId()))
filteredGrantees := s.filter.execute(ctx, granteeList, defaults.SettingUUIDProfileEventShareExpired)
recipientsInstant, recipientsDaily, recipientsInstantWeekly := s.splitter.execute(ctx, filteredGrantees)
@@ -183,7 +184,7 @@ func (s eventsNotifier) handleShareRemoved(baseCtx context.Context, e events.Sha
return
}
granteeList := s.ensureGranteeList(ctx, executant.GetId(), e.GranteeUserID, e.GranteeGroupID)
granteeList := s.ensureGranteeList(ctx, executant.GetId(), e.GranteeUserID, e.GranteeGroupID, vault.IsVaultStorage(e.ItemID.GetStorageId()))
filteredGrantees := s.filter.execute(ctx, granteeList, defaults.SettingUUIDProfileEventShareRemoved)
recipientsInstant, recipientsDaily, recipientsInstantWeekly := s.splitter.execute(ctx, filteredGrantees)
+4 -3
View File
@@ -4,6 +4,7 @@ import (
"context"
user "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
"github.com/owncloud/ocis/v2/ocis-pkg/vault"
"github.com/owncloud/ocis/v2/services/notifications/pkg/email"
"github.com/owncloud/ocis/v2/services/settings/pkg/store/defaults"
"github.com/owncloud/reva/v2/pkg/events"
@@ -23,7 +24,7 @@ func (s eventsNotifier) handleSpaceShared(baseCtx context.Context, e events.Spac
return
}
granteeList := s.ensureGranteeList(ctx, executant.GetId(), e.GranteeUserID, e.GranteeGroupID)
granteeList := s.ensureGranteeList(ctx, executant.GetId(), e.GranteeUserID, e.GranteeGroupID, vault.IsVaultSpace(e.ID.GetOpaqueId()))
filteredGrantees := s.filter.execute(ctx, granteeList, defaults.SettingUUIDProfileEventSpaceShared)
recipientsInstant, recipientsDaily, recipientsInstantWeekly := s.splitter.execute(ctx, filteredGrantees)
@@ -108,7 +109,7 @@ func (s eventsNotifier) handleSpaceUnshared(baseCtx context.Context, e events.Sp
return
}
granteeList := s.ensureGranteeList(ctx, executant.GetId(), e.GranteeUserID, e.GranteeGroupID)
granteeList := s.ensureGranteeList(ctx, executant.GetId(), e.GranteeUserID, e.GranteeGroupID, vault.IsVaultSpace(e.ID.GetOpaqueId()))
filteredGrantees := s.filter.execute(ctx, granteeList, defaults.SettingUUIDProfileEventSpaceUnshared)
recipientsInstant, recipientsDaily, recipientsInstantWeekly := s.splitter.execute(ctx, filteredGrantees)
@@ -207,7 +208,7 @@ func (s eventsNotifier) handleSpaceMembershipExpired(baseCtx context.Context, e
return
}
granteeList := s.ensureGranteeList(ctx, owner.GetId(), e.GranteeUserID, e.GranteeGroupID)
granteeList := s.ensureGranteeList(ctx, owner.GetId(), e.GranteeUserID, e.GranteeGroupID, vault.IsVaultSpace(e.SpaceID.GetOpaqueId()))
if granteeList == nil {
return
}
+41
View File
@@ -21,6 +21,7 @@ import (
"github.com/owncloud/ocis/v2/ocis-pkg/l10n"
"github.com/owncloud/ocis/v2/ocis-pkg/log"
"github.com/owncloud/ocis/v2/ocis-pkg/roles"
"github.com/owncloud/ocis/v2/ocis-pkg/vault"
ehmsg "github.com/owncloud/ocis/v2/protogen/gen/ocis/messages/eventhistory/v0"
ehsvc "github.com/owncloud/ocis/v2/protogen/gen/ocis/services/eventhistory/v0"
settingssvc "github.com/owncloud/ocis/v2/protogen/gen/ocis/services/settings/v0"
@@ -207,6 +208,9 @@ func (ul *UserlogService) processEvent(event events.Event) {
// II) filter users who want to receive the event
users = ul.filter.execute(ctx, event, executant, users)
if isVaultEvent(event) {
users = ul.filterVaultUsers(ctx, gwc, users)
}
// III) store the eventID for each user
for _, id := range users {
@@ -224,6 +228,43 @@ func (ul *UserlogService) processEvent(event events.Event) {
}
}
// isVaultEvent reports whether the event is about a share or a space membership in the vault.
func isVaultEvent(event events.Event) bool {
switch e := event.Event.(type) {
case events.ShareCreated:
return vault.IsVaultStorage(e.ItemID.GetStorageId())
case events.ShareRemoved:
return vault.IsVaultStorage(e.ItemID.GetStorageId())
case events.ShareExpired:
return vault.IsVaultStorage(e.ItemID.GetStorageId())
case events.SpaceShared:
return vault.IsVaultSpace(e.ID.GetOpaqueId())
case events.SpaceUnshared:
return vault.IsVaultSpace(e.ID.GetOpaqueId())
case events.SpaceMembershipExpired:
return vault.IsVaultSpace(e.SpaceID.GetOpaqueId())
default:
return false
}
}
// filterVaultUsers keeps only the users who hold the VaultMode permission.
func (ul *UserlogService) filterVaultUsers(ctx context.Context, gwc gateway.GatewayAPIClient, users []string) []string {
ids := make([]*user.UserId, 0, len(users))
for _, u := range users {
ids = append(ids, &user.UserId{OpaqueId: u})
}
allowed := vault.FilterVaultModeUsers(ctx, gwc, ids, func(id *user.UserId, err error) {
ul.log.Error().Err(err).Str("userId", id.GetOpaqueId()).Msg("could not check the vault permission, user skipped")
})
filtered := make([]string, 0, len(allowed))
for _, id := range allowed {
filtered = append(filtered, id.GetOpaqueId())
}
return filtered
}
// GetEvents allows retrieving events from the eventhistory by userid
func (ul *UserlogService) GetEvents(ctx context.Context, userid string) ([]*ehmsg.Event, error) {
ctx, span := ul.tracer.Start(ctx, "GetEvents")
+182
View File
@@ -0,0 +1,182 @@
package service_test
import (
"context"
"encoding/json"
"time"
gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1"
group "github.com/cs3org/go-cs3apis/cs3/identity/group/v1beta1"
user "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
permissions "github.com/cs3org/go-cs3apis/cs3/permissions/v1beta1"
rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1"
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
"github.com/go-chi/chi/v5"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/owncloud/reva/v2/pkg/events"
"github.com/owncloud/reva/v2/pkg/rgrpc/todo/pool"
"github.com/owncloud/reva/v2/pkg/storagespace"
"github.com/owncloud/reva/v2/pkg/store"
"github.com/owncloud/reva/v2/pkg/utils"
cs3mocks "github.com/owncloud/reva/v2/tests/cs3mocks/mocks"
"github.com/stretchr/testify/mock"
"go-micro.dev/v4/client"
microstore "go-micro.dev/v4/store"
"go.opentelemetry.io/otel/trace"
"google.golang.org/grpc"
"github.com/owncloud/ocis/v2/ocis-pkg/log"
settingsmsg "github.com/owncloud/ocis/v2/protogen/gen/ocis/messages/settings/v0"
"github.com/owncloud/ocis/v2/protogen/gen/ocis/services/eventhistory/v0/mocks"
settingssvc "github.com/owncloud/ocis/v2/protogen/gen/ocis/services/settings/v0"
"github.com/owncloud/ocis/v2/services/userlog/pkg/config"
"github.com/owncloud/ocis/v2/services/userlog/pkg/service"
)
var _ = Describe("UserlogService vault events", func() {
const (
member = "member"
outsider = "outsider"
)
var (
bus testBus
sto microstore.Store
gatewayClient *cs3mocks.GatewayAPIClient
checkedUsers chan string
vaultResourceID = &provider.ResourceId{
StorageId: utils.VaultStorageProviderID,
SpaceId: "spaceid",
OpaqueId: "itemid",
}
regularResourceID = &provider.ResourceId{
StorageId: "storageid",
SpaceId: "spaceid",
OpaqueId: "itemid",
}
vaultSpaceID = &provider.StorageSpaceId{
OpaqueId: storagespace.FormatResourceID(&provider.ResourceId{
StorageId: utils.VaultStorageProviderID,
SpaceId: "vaultspaceid",
OpaqueId: "vaultspaceid",
}),
}
vaultGroup = &group.GroupId{OpaqueId: "vaultgroup"}
)
BeforeEach(func() {
sto = store.Create()
bus = testBus(make(chan events.Event))
checkedUsers = make(chan string, 10)
pool.RemoveSelector("GatewaySelector" + "com.owncloud.api.gateway")
gatewayClient = &cs3mocks.GatewayAPIClient{}
gatewaySelector := pool.GetSelector[gateway.GatewayAPIClient](
"GatewaySelector",
"com.owncloud.api.gateway",
func(cc grpc.ClientConnInterface) gateway.GatewayAPIClient {
return gatewayClient
},
)
gatewayClient.On("Authenticate", mock.Anything, mock.Anything).Return(&gateway.AuthenticateResponse{Status: &rpc.Status{Code: rpc.Code_CODE_OK}}, nil)
gatewayClient.On("GetGroup", mock.Anything, mock.Anything).Return(&group.GetGroupResponse{
Status: &rpc.Status{Code: rpc.Code_CODE_OK},
Group: &group.Group{Members: []*user.UserId{{OpaqueId: member}, {OpaqueId: outsider}}},
}, nil)
gatewayClient.On("CheckPermission", mock.Anything, mock.Anything).Return(func(_ context.Context, r *permissions.CheckPermissionRequest, _ ...grpc.CallOption) (*permissions.CheckPermissionResponse, error) {
id := r.GetSubjectRef().GetUserId().GetOpaqueId()
checkedUsers <- id
code := rpc.Code_CODE_PERMISSION_DENIED
if id == member {
code = rpc.Code_CODE_OK
}
return &permissions.CheckPermissionResponse{Status: &rpc.Status{Code: code}}, nil
})
vc := &settingssvc.MockValueService{}
vc.GetValueByUniqueIdentifiersFunc = func(ctx context.Context, req *settingssvc.GetValueByUniqueIdentifiersRequest, opts ...client.CallOption) (*settingssvc.GetValueResponse, error) {
return &settingssvc.GetValueResponse{
Value: &settingsmsg.ValueWithIdentifier{
Value: &settingsmsg.Value{
Value: &settingsmsg.Value_CollectionValue{
CollectionValue: &settingsmsg.CollectionValue{
Values: []*settingsmsg.CollectionOption{
{
Key: "in-app",
Option: &settingsmsg.CollectionOption_BoolValue{BoolValue: true},
},
},
},
},
},
},
}, nil
}
_, err := service.NewUserlogService(
service.Config(&config.Config{MaxConcurrency: 5, DisableSSE: true}),
service.Stream(bus),
service.Store(sto),
service.Logger(log.NewLogger()),
service.Mux(chi.NewMux()),
service.GatewaySelector(gatewaySelector),
service.HistoryClient(&mocks.EventHistoryService{}),
service.ValueClient(vc),
service.RegisteredEvents([]events.Unmarshaller{
events.ShareCreated{},
events.SpaceShared{},
}),
service.TraceProvider(trace.NewNoopTracerProvider()),
)
Expect(err).ToNot(HaveOccurred())
})
AfterEach(func() {
close(bus)
})
storedEvents := func(userID string) []string {
recs, err := sto.Read(userID)
if err != nil {
return nil
}
var ids []string
Expect(json.Unmarshal(recs[0].Value, &ids)).To(Succeed())
return ids
}
DescribeTable("stores the event only for group members with the vault mode permission",
func(ev interface{}) {
id := bus.publish(ev)
Eventually(func() []string { return storedEvents(member) }, time.Second).Should(ConsistOf(id))
Consistently(func() []string { return storedEvents(outsider) }, 200*time.Millisecond).Should(BeEmpty())
},
Entry("Share Created", events.ShareCreated{
Executant: &user.UserId{OpaqueId: "sharer"},
GranteeGroupID: vaultGroup,
ItemID: vaultResourceID,
}),
Entry("Added to Space", events.SpaceShared{
Executant: &user.UserId{OpaqueId: "sharer"},
GranteeGroupID: vaultGroup,
ID: vaultSpaceID,
}),
)
It("does not check the vault mode permission for a regular resource", func() {
id := bus.publish(events.ShareCreated{
Executant: &user.UserId{OpaqueId: "sharer"},
GranteeGroupID: vaultGroup,
ItemID: regularResourceID,
})
Eventually(func() []string { return storedEvents(member) }, time.Second).Should(ConsistOf(id))
Eventually(func() []string { return storedEvents(outsider) }, time.Second).Should(ConsistOf(id))
Expect(checkedUsers).To(BeEmpty())
})
})
+1
View File
@@ -503,6 +503,7 @@ default:
- SpacesContext:
- SharingNgContext:
- OCSContext:
- NotificationContext:
cliCommands:
paths:
+101 -23
View File
@@ -1191,11 +1191,12 @@ Feature: vault
| vaultFile.txt | File Editor |
Scenario: try to send share invitation for a resource in vault to a group
Scenario: send share invitation for a resource in vault to a group
Given these groups have been created:
| groupname |
| vault-group |
And user "Brian" has been created with default attributes
And the administrator has assigned the role "Space Admin" to user "Brian" using the Graph API
And user "Brian" has been set up in oCIS
And user "Brian" has been added to group "vault-group"
And user "Alice" has been set up in oCIS
@@ -1207,28 +1208,105 @@ Feature: vault
| shareType | group |
| permissionsRole | Viewer |
| storage | vault |
Then the HTTP status code should be "403"
And the JSON data of the response should match
"""
{
"type": "object",
"required": ["error"],
"properties": {
"error": {
"type": "object",
"required": ["code", "message"],
"properties": {
"code": {
"const": "accessDenied"
},
"message": {
"const": "grantee is not allowed to access vault resources"
}
}
}
}
}
"""
Then the HTTP status code should be "200"
And user "Brian" should have a share in vault "vaultFile.txt" synced
And user "Brian" should have the following resource shares:
| resource | permissionsRole | sharer | space | storage |
| vaultFile.txt | Viewer | Alice | Personal | vault |
Scenario Outline: only group members with the vault mode permission get a notification and access for a vault share
Given these users have been created with default attributes:
| username |
| Brian |
| Carol |
And the administrator has assigned the role "<vault-role>" to user "Brian" using the Graph API
And the administrator has assigned the role "<no-vault-role>" to user "Carol" using the Graph API
And these groups have been created:
| groupname |
| vault-group |
And user "Brian" has been added to group "vault-group"
And user "Carol" has been added to group "vault-group"
And user "Alice" has been set up in oCIS
And user "Brian" has been set up in oCIS
And user "Carol" has been set up in oCIS
And user "Alice" has uploaded a file inside space "Personal" with content "some content" to "vaultFile.txt" in vault
And we save it into "FILEID"
When user "Alice" sends the following resource share invitation using the Graph API:
| resource | vaultFile.txt |
| space | Personal |
| sharee | vault-group |
| shareType | group |
| permissionsRole | Viewer |
| storage | vault |
Then the HTTP status code should be "200"
And user "Brian" should have a share in vault "vaultFile.txt" synced
# Check Brian first. The userlog service filters all group members before it stores the
# notification for one of them, so the check for Carol cannot run too early.
And user "Brian" should get a notification with subject "Resource shared" and message:
| message |
| Alice Hansen shared vaultFile.txt with you |
And user "Carol" should not have any notification
When user "Brian" sends HTTP method "GET" to URL "/dav/spaces/<<FILEID>>"
Then the HTTP status code should be "200"
And the downloaded content should be "some content"
When user "Carol" tries to send HTTP method "GET" to URL "/dav/spaces/<<FILEID>>"
Then the HTTP status code should be "403" or "404"
And for user "Carol" the space "Shares" should not contain these entries:
| vaultFile.txt |
Examples:
| vault-role | no-vault-role |
| Space Admin | User Light |
| Admin | User |
Scenario Outline: only group members with the vault mode permission get a notification and access for a vault space membership
Given these users have been created with default attributes:
| username |
| Brian |
| Carol |
And the administrator has assigned the role "<vault-role>" to user "Brian" using the Graph API
And the administrator has assigned the role "<no-vault-role>" to user "Carol" using the Graph API
And these groups have been created:
| groupname |
| vault-group |
And user "Brian" has been added to group "vault-group"
And user "Carol" has been added to group "vault-group"
And user "Alice" has been set up in oCIS
And user "Brian" has been set up in oCIS
And user "Carol" has been set up in oCIS
And user "Alice" has created a space "new-space" in vault with the default quota using the Graph API
And user "Alice" has uploaded a file inside space "new-space" with content "some content" to "vaultFile.txt" in vault
And we save it into "FILEID"
When user "Alice" sends the following space share invitation using root endpoint of the Graph API:
| space | new-space |
| sharee | vault-group |
| shareType | group |
| permissionsRole | <permissions-role> |
| storage | vault |
Then the HTTP status code should be "200"
# Check Brian first. The userlog service filters all group members before it stores the
# notification for one of them, so the check for Carol cannot run too early.
And user "Brian" should get a notification with subject "Space shared" and message:
| message |
| Alice Hansen added you to Space new-space |
And user "Carol" should not have any notification
And for user "Brian" the space "new-space" in vault should contain these entries:
| vaultFile.txt |
When user "Brian" sends HTTP method "GET" to URL "/dav/spaces/<<FILEID>>"
Then the HTTP status code should be "200"
And the downloaded content should be "some content"
When user "Carol" tries to send HTTP method "GET" to URL "/dav/spaces/<<FILEID>>"
Then the HTTP status code should be "403" or "404"
When user "Carol" lists all available spaces via the Graph API
Then the HTTP status code should be "200"
And the json response should not contain a space with name "new-space"
Examples:
| permissions-role | vault-role | no-vault-role |
| Manager | Space Admin | User Light |
| Manager | Admin | User |
| Space Viewer | Space Admin | User Light |
| Space Editor | Admin | User |
Scenario Outline: server sets a default 30-day expiration when a user share is created without one
@@ -63,6 +63,10 @@ type config struct {
UserGroupsCacheSize int `mapstructure:"usergroups_cache_size"`
ScopeExpansionCacheSize int `mapstructure:"scope_expansion_cache_size"`
MFAEnabled bool `mapstructure:"mfa_enabled"`
// VaultModeRequired denies access to users who do not hold the VaultMode permission.
VaultModeRequired bool `mapstructure:"vault_mode_required"`
VaultModeCacheSize int `mapstructure:"vault_mode_cache_size"`
VaultModeCacheSeconds int `mapstructure:"vault_mode_cache_seconds"`
}
func parseConfig(m map[string]interface{}) (*config, error) {
@@ -71,6 +75,13 @@ func parseConfig(m map[string]interface{}) (*config, error) {
err = errors.Wrap(err, "auth: error decoding conf")
return nil, err
}
if c.VaultModeCacheSize == 0 {
c.VaultModeCacheSize = 5000
}
if c.VaultModeCacheSeconds == 0 {
c.VaultModeCacheSeconds = 30
}
initVaultModeCache(c.VaultModeCacheSize, time.Duration(c.VaultModeCacheSeconds)*time.Second)
return c, nil
}
@@ -163,6 +174,16 @@ func NewUnary(m map[string]interface{}, unprotected []string, tp trace.TracerPro
return mfaResponse(ctx, req, info)
}
}
if conf.VaultModeRequired && u.Id.Type != userpb.UserType_USER_TYPE_SERVICE {
allowed, err := hasVaultMode(ctx, u, conf.GatewayAddr)
if err != nil {
log.Error().Err(err).Str("user_id", u.Id.OpaqueId).Msg("could not check the vault mode permission")
}
if !allowed {
log.Debug().Str("user_id", u.Id.OpaqueId).Msg("vault mode permission is required")
return denyResponse(ctx, req, info, vaultModeRequiredMsg)
}
}
span.SetAttributes(semconv.EnduserIDKey.String(u.Id.OpaqueId))
@@ -182,6 +203,7 @@ func NewStream(m map[string]interface{}, unprotected []string, tp trace.TracerPr
if conf.TokenManager == "" {
conf.TokenManager = "jwt"
}
conf.GatewayAddr = sharedconf.GetGatewaySVC(conf.GatewayAddr)
if conf.UserGroupsCacheSize == 0 {
conf.UserGroupsCacheSize = 10000
@@ -260,6 +282,16 @@ func NewStream(m map[string]interface{}, unprotected []string, tp trace.TracerPr
return status.Errorf(codes.PermissionDenied, "MFA required to access vault storage")
}
}
if conf.VaultModeRequired && u.Id.Type != userpb.UserType_USER_TYPE_SERVICE {
allowed, err := hasVaultMode(ctx, u, conf.GatewayAddr)
if err != nil {
log.Error().Err(err).Str("user_id", u.Id.OpaqueId).Msg("could not check the vault mode permission")
}
if !allowed {
log.Debug().Str("user_id", u.Id.OpaqueId).Msg("vault mode permission is required")
return status.Errorf(codes.PermissionDenied, vaultModeRequiredMsg)
}
}
wrapped := newWrappedServerStream(ctx, ss)
span.SetAttributes(semconv.EnduserIDKey.String(u.Id.OpaqueId))
+7 -3
View File
@@ -12,7 +12,11 @@ import (
)
func mfaResponse(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo) (interface{}, error) {
const msg = "MFA required to access vault storage"
return denyResponse(ctx, req, info, "MFA required to access vault storage")
}
// denyResponse returns a PERMISSION_DENIED response of the type that matches the request.
func denyResponse(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, msg string) (interface{}, error) {
switch req.(type) {
case *provider.StatRequest:
return &provider.StatResponse{Status: rstatus.NewPermissionDenied(ctx, nil, msg)}, nil
@@ -67,7 +71,7 @@ func mfaResponse(ctx context.Context, req interface{}, info *grpc.UnaryServerInf
case *provider.DeleteStorageSpaceRequest:
return &provider.DeleteStorageSpaceResponse{Status: rstatus.NewPermissionDenied(ctx, nil, msg)}, nil
default:
log.Debug().Str("method", info.FullMethod).Msg("mfa: blocking unknown request type")
return nil, grpcstatus.Errorf(codes.PermissionDenied, "mfa: %s: %T", msg, req)
log.Debug().Str("method", info.FullMethod).Msg("auth: blocking unknown request type")
return nil, grpcstatus.Errorf(codes.PermissionDenied, "auth: %s: %T", msg, req)
}
}
@@ -0,0 +1,75 @@
package auth
import (
"context"
"sync"
"time"
"github.com/bluele/gcache"
gatewayv1beta1 "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1"
userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
permissions "github.com/cs3org/go-cs3apis/cs3/permissions/v1beta1"
rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1"
"github.com/owncloud/reva/v2/pkg/permission"
"github.com/owncloud/reva/v2/pkg/rgrpc/todo/pool"
"github.com/pkg/errors"
)
const vaultModeRequiredMsg = "vault mode permission required to access vault storage"
var (
vaultModeCache gcache.Cache
vaultModeCacheTTL time.Duration
vaultModeCacheOnce sync.Once
// getGatewayClient is a variable, so that tests can replace the gateway client.
getGatewayClient = func(addr string) (gatewayv1beta1.GatewayAPIClient, error) {
return pool.GetGatewayServiceClient(addr)
}
)
// initVaultModeCache creates the cache for the VaultMode answers. Only the first call has an effect.
func initVaultModeCache(size int, ttl time.Duration) {
vaultModeCacheOnce.Do(func() {
vaultModeCache = gcache.New(size).LRU().Build()
vaultModeCacheTTL = ttl
})
}
// hasVaultMode reports whether the user holds the VaultMode permission.
// The vault storage provider uses it to deny access to users who cannot use vault mode,
// for example group members who received a vault share. A non-nil error means undetermined,
// so the caller must deny the request. Only definitive answers are cached.
func hasVaultMode(ctx context.Context, u *userpb.User, gatewayAddr string) (bool, error) {
id := u.GetId().GetOpaqueId()
if v, err := vaultModeCache.Get(id); err == nil {
return v.(bool), nil
}
client, err := getGatewayClient(gatewayAddr)
if err != nil {
return false, err
}
res, err := client.CheckPermission(ctx, &permissions.CheckPermissionRequest{
SubjectRef: &permissions.SubjectReference{
Spec: &permissions.SubjectReference_UserId{UserId: u.GetId()},
},
Permission: permission.VaultMode,
})
if err != nil {
return false, errors.Wrap(err, "auth: error calling CheckPermission")
}
var allowed bool
switch code := res.GetStatus().GetCode(); code {
case rpc.Code_CODE_OK:
allowed = true
case rpc.Code_CODE_PERMISSION_DENIED:
allowed = false
default:
return false, errors.Errorf("auth: vault permission check returned status %q: %s", code, res.GetStatus().GetMessage())
}
_ = vaultModeCache.SetWithExpire(id, allowed, vaultModeCacheTTL)
return allowed, nil
}
@@ -78,6 +78,13 @@ func (s *svc) CreateShare(ctx context.Context, req *collaboration.CreateShareReq
// granteeMayAccessVault reports whether the grantee may be granted access to a vault resource.
// A non-nil error means undetermined, never denied, so callers must fail closed.
func (s *svc) granteeMayAccessVault(ctx context.Context, g *provider.Grantee) (bool, error) {
// Groups are allowed without a VaultMode check. Role assignments belong to single accounts,
// and group membership can change after the share exists. The notification services filter
// the group members by VaultMode instead, and every member still needs MFA to open the vault.
if g.GetType() == provider.GranteeType_GRANTEE_TYPE_GROUP {
return g.GetGroupId().GetOpaqueId() != "", nil
}
ref := vaultPermissionSubject(g)
if ref == nil {
return false, nil
@@ -93,7 +100,8 @@ func (s *svc) granteeMayAccessVault(ctx context.Context, g *provider.Grantee) (b
return vaultPermissionGranted(res.GetStatus())
}
// vaultPermissionSubject returns the subject to check VaultMode for, or nil for grantees that can never hold it, like groups.
// vaultPermissionSubject returns the subject to check VaultMode for, or nil for grantees that cannot hold it.
// Groups cannot hold it, because role assignments belong to single accounts.
func vaultPermissionSubject(g *provider.Grantee) *permissions.SubjectReference {
if g.GetType() != provider.GranteeType_GRANTEE_TYPE_USER {
return nil
+1 -1
View File
@@ -1321,7 +1321,7 @@ github.com/orcaman/concurrent-map
# github.com/owncloud/libre-graph-api-go v1.0.5-0.20260216101009-eeac018af245
## explicit; go 1.18
github.com/owncloud/libre-graph-api-go
# github.com/owncloud/reva/v2 v2.0.0-20261022133635-764ed1d17629
# github.com/owncloud/reva/v2 v2.0.0-20261028142447-7ce5132a4574
## explicit; go 1.26.0
github.com/owncloud/reva/v2/cmd/revad/internal/grace
github.com/owncloud/reva/v2/cmd/revad/runtime
@@ -105,6 +105,23 @@
/>
</div>
</div>
<div id="vault-group-notice-status" role="status">
<div
v-if="showVaultGroupNotice"
class="oc-flex oc-flex-middle oc-gap-s oc-background-muted oc-rounded oc-p-s oc-mb-s oc-text-small"
data-testid="vault-group-notice"
>
<oc-icon name="information" size="small" aria-hidden="true" />
<span
v-text="
$pgettext(
'Notice shown when sharing a resource inside the vault with a group',
'Group members without vault access will not receive a notification and cannot access the share.'
)
"
/>
</div>
</div>
<div class="oc-flex oc-flex-between oc-flex-middle oc-mb-l oc-mt-s">
<role-dropdown
mode="create"
@@ -199,7 +216,7 @@ import {
} from '@ownclouders/web-pkg'
import { computed, inject, ref, unref, watch, onMounted, nextTick, Ref, useTemplateRef } from 'vue'
import { Resource, SpaceResource, VAULT_STORAGE_PROVIDER_ID } from '@ownclouders/web-client'
import { Resource, SpaceResource } from '@ownclouders/web-client'
import { DateTime } from 'luxon'
import { OcDrop } from '@ownclouders/design-system/components'
import { useTask } from 'vue-concurrency'
@@ -207,6 +224,7 @@ import { useGettext } from 'vue3-gettext'
import { isProjectSpaceResource } from '@ownclouders/web-client'
import { Group } from '@ownclouders/web-client/graph/generated'
import ExpirationDateIndicator from '../../ExpirationDateIndicator.vue'
import { isVaultResource as isVaultResourceHelper } from '../../../../../helpers/resource/vault'
type AccountType = {
prefix: string
@@ -317,15 +335,17 @@ const accountTypes: AccountType[] = [
]
const saveButtonText = computed(() => saveButtonLabel || $gettext('Share'))
// A resource lives in the vault if its storage provider is the vault one. Space resources carry
// the full drive id in storageId, plain resources only the provider id, hence the split.
const isVaultResource = computed(() => {
const storageId = unref(resource)?.storageId
if (!unref(capabilityRefs.vaultEnabled) || typeof storageId !== 'string') {
return false
}
return storageId.split('$')[0] === VAULT_STORAGE_PROVIDER_ID
})
const isVaultResource = computed(() =>
isVaultResourceHelper(unref(resource), unref(capabilityRefs.vaultEnabled))
)
// group members without vault access are filtered out by the server when it sends the share
// notifications, and they can't open the resource either
const showVaultGroupNotice = computed(
() =>
unref(isVaultResource) &&
unref(selectedCollaborators).some(({ shareType }) => shareType === ShareTypes.group.value)
)
// no local fallback: the default lives only in the server's vault config
const vaultDefaultExpirationDays = capabilityRefs.vaultDefaultShareExpirationDays
@@ -356,9 +376,9 @@ const fetchRecipientsTask = useTask(function* (signal, query: string) {
)
let groupData: Group[]
if (!unref(isExternalShareRoleType) && !unref(isVaultResource)) {
// groups are only available for internal shares, and never for vault resources: the
// vault permission is assigned per account, so a group can never hold it
if (!unref(isExternalShareRoleType)) {
// groups are only available for internal shares. For vault resources the server checks
// the vault permission of each group member when it sends the share notifications
groupData = yield* call(
client.groups.listGroups({ orderBy: ['displayName'], search: `"${query}"` }, { signal })
)
@@ -110,6 +110,7 @@ import {
} from '@ownclouders/web-pkg'
import { isLocationSharesActive } from '@ownclouders/web-pkg'
import { textUtils } from '../../../helpers/textUtils'
import { isVaultResource } from '../../../helpers/resource/vault'
import { isShareSpaceResource, ShareTypes } from '@ownclouders/web-client'
import InviteCollaboratorForm from './Collaborators/InviteCollaborator/InviteCollaboratorForm.vue'
import CollaboratorListItem from './Collaborators/ListItem.vue'
@@ -144,7 +145,11 @@ const { getSpaceMembers } = useSpacesStore()
const configStore = useConfigStore()
const { options: configOptions } = storeToRefs(configStore)
const { shareInviteCollaboratorHelp, shareInviteCollaboratorHelpCern } = useContextualHelpers()
const {
shareInviteCollaboratorHelp,
shareInviteCollaboratorHelpCern,
shareInviteCollaboratorHelpVault
} = useContextualHelpers()
const sharesStore = useSharesStore()
const { addShare, deleteShare } = sharesStore
@@ -203,14 +208,17 @@ const collaborators = computed(() => {
const inviteCollaboratorHelp = computed(() => {
const cernFeatures = configOptions.value.cernFeatures
const mergedHelp = { ...unref(shareInviteCollaboratorHelp) }
if (cernFeatures) {
const mergedHelp = { ...unref(shareInviteCollaboratorHelp) }
mergedHelp.list = [...unref(shareInviteCollaboratorHelpCern).list, ...mergedHelp.list]
return mergedHelp
}
return unref(shareInviteCollaboratorHelp)
if (isVaultResource(unref(resource), capabilityStore.vaultEnabled)) {
mergedHelp.list = [...mergedHelp.list, ...unref(shareInviteCollaboratorHelpVault).list]
}
return mergedHelp
})
const helpersEnabled = computed(() => {
@@ -63,6 +63,20 @@ export const useContextualHelpers = () => {
})
)
const shareInviteCollaboratorHelpVault = computed<ContextualHelperData>(() =>
filterContextHelper({
title: '',
list: [
{ text: $gettext('Groups in the vault'), headline: true },
{
text: $gettext(
'If you share with a group, only group members with vault access will receive a notification and can access the share.'
)
}
]
})
)
const shareSpaceAddMemberHelp = computed<ContextualHelperData>(() =>
filterContextHelper({
title: $gettext('Add members to this Space'),
@@ -134,6 +148,7 @@ export const useContextualHelpers = () => {
return {
shareInviteCollaboratorHelp,
shareInviteCollaboratorHelpCern,
shareInviteCollaboratorHelpVault,
shareSpaceAddMemberHelp,
shareViaLinkHelp,
shareViaIndirectLinkHelp,
@@ -0,0 +1,11 @@
import { Resource, VAULT_STORAGE_PROVIDER_ID } from '@ownclouders/web-client'
// A resource lives in the vault if its storage provider is the vault one. Space resources carry
// the full drive id in storageId, plain resources only the provider id, hence the split.
export const isVaultResource = (resource: Resource, vaultEnabled: boolean): boolean => {
const storageId = resource?.storageId
if (!vaultEnabled || typeof storageId !== 'string') {
return false
}
return storageId.split('$')[0] === VAULT_STORAGE_PROVIDER_ID
}
@@ -10,7 +10,12 @@ import {
} from '@ownclouders/web-test-helpers'
import { Resource, SpaceResource, VAULT_STORAGE_PROVIDER_ID } from '@ownclouders/web-client'
import { useSharesStore } from '@ownclouders/web-pkg'
import { CollaboratorAutoCompleteItem, CollaboratorShare, ShareRole } from '@ownclouders/web-client'
import {
CollaboratorAutoCompleteItem,
CollaboratorShare,
ShareRole,
ShareTypes
} from '@ownclouders/web-client'
import { Group, User } from '@ownclouders/web-client/graph/generated'
import { OcButton } from '@ownclouders/design-system/components'
import RoleDropdown from '../../../../../../../src/components/SideBar/Shares/Collaborators/RoleDropdown.vue'
@@ -122,7 +127,7 @@ describe('InviteCollaboratorForm', () => {
vault: { enabled: true, vault_storage_provider: '' }
}
it('only asks for users that may access the vault, and for no groups at all', async () => {
it('asks for users that may access the vault, and for groups', async () => {
const { wrapper, mocks } = getWrapper({
capabilities: vaultCapabilities,
resource: mock<Resource>({ ...folderMock, storageId: VAULT_STORAGE_PROVIDER_ID })
@@ -133,7 +138,7 @@ describe('InviteCollaboratorForm', () => {
expect.objectContaining({ filter: 'vaultEligible eq true' }),
expect.anything()
)
expect(mocks.$clientService.graphAuthenticated.groups.listGroups).not.toHaveBeenCalled()
expect(mocks.$clientService.graphAuthenticated.groups.listGroups).toHaveBeenCalled()
})
it('recognizes a vault space resource, which carries the full drive id', async () => {
const { wrapper, mocks } = getWrapper({
@@ -179,6 +184,49 @@ describe('InviteCollaboratorForm', () => {
)
})
})
describe('vault group notice', () => {
const vaultCapabilities = {
files_sharing: { federation: { incoming: true, outgoing: true } },
vault: { enabled: true, vault_storage_provider: '' }
}
it('shows when a group is selected for a vault resource', async () => {
const { wrapper } = getWrapper({
capabilities: vaultCapabilities,
resource: mock<Resource>({ ...folderMock, storageId: VAULT_STORAGE_PROVIDER_ID })
})
wrapper.vm.selectedCollaborators = [
mock<CollaboratorAutoCompleteItem>({ shareType: ShareTypes.group.value })
]
await wrapper.vm.$nextTick()
expect(wrapper.find('[data-testid="vault-group-notice"]').exists()).toBeTruthy()
})
it('does not show when only users are selected', async () => {
const { wrapper } = getWrapper({
capabilities: vaultCapabilities,
resource: mock<Resource>({ ...folderMock, storageId: VAULT_STORAGE_PROVIDER_ID })
})
wrapper.vm.selectedCollaborators = [
mock<CollaboratorAutoCompleteItem>({ shareType: ShareTypes.user.value })
]
await wrapper.vm.$nextTick()
expect(wrapper.find('[data-testid="vault-group-notice"]').exists()).toBeFalsy()
})
it('does not show for a group outside the vault', async () => {
const { wrapper } = getWrapper({
capabilities: vaultCapabilities,
resource: mock<Resource>({ ...folderMock, storageId: 'some-other-provider' })
})
wrapper.vm.selectedCollaborators = [
mock<CollaboratorAutoCompleteItem>({ shareType: ShareTypes.group.value })
]
await wrapper.vm.$nextTick()
expect(wrapper.find('[data-testid="vault-group-notice"]').exists()).toBeFalsy()
})
})
describe('vault default expiration notice', () => {
const vaultCapabilities = {
files_sharing: { federation: { incoming: true, outgoing: true } },
@@ -1,6 +1,6 @@
import FileShares from '../../../../../src/components/SideBar/Shares/FileShares.vue'
import { mock } from 'vitest-mock-extended'
import { Resource } from '@ownclouders/web-client'
import { Resource, VAULT_STORAGE_PROVIDER_ID } from '@ownclouders/web-client'
import { SpaceResource } from '@ownclouders/web-client'
import { v4 as uuidV4 } from 'uuid'
import { CollaboratorShare, ShareRole, ShareTypes } from '@ownclouders/web-client'
@@ -53,6 +53,35 @@ describe('FileShares', () => {
})
})
describe('invite collaborator help', () => {
const hasVaultGroupHint = (wrapper: VueWrapper<any, any>) =>
wrapper.vm.inviteCollaboratorHelp.list.some(
({ text }: { text: string }) => text === 'Groups in the vault'
)
it('explains group shares for a vault resource', () => {
const { wrapper } = getWrapper({
vaultEnabled: true,
resource: mock<Resource>({
isReceivedShare: () => false,
canShare: () => true,
storageId: VAULT_STORAGE_PROVIDER_ID
})
})
expect(hasVaultGroupHint(wrapper)).toBeTruthy()
})
it('does not explain group shares for a resource outside the vault', () => {
const { wrapper } = getWrapper({
vaultEnabled: true,
resource: mock<Resource>({
isReceivedShare: () => false,
canShare: () => true,
storageId: 'some-other-provider'
})
})
expect(hasVaultGroupHint(wrapper)).toBeFalsy()
})
})
describe('collaborators list', () => {
let collaborators: CollaboratorShare[]
beforeEach(() => {
@@ -169,7 +198,8 @@ function getWrapper({
spaceMembers = [],
user = undefined,
ancestorMetaData = {},
canShare = true
canShare = true,
vaultEnabled = false
}: {
mountType?: typeof mount
resource?: Resource
@@ -179,11 +209,13 @@ function getWrapper({
user?: User
ancestorMetaData?: AncestorMetaData
canShare?: boolean
vaultEnabled?: boolean
} = {}) {
vi.mocked(useCanShare).mockReturnValue({ canShare: () => canShare })
const capabilities = {
files_sharing: { deny_access: false }
files_sharing: { deny_access: false },
vault: { enabled: vaultEnabled }
} satisfies Partial<CapabilityStore['capabilities']>
if (spaceMembers.length) {