diff --git a/changelog/unreleased/bugfix-sharedwithme-degraded-items.md b/changelog/unreleased/bugfix-sharedwithme-degraded-items.md new file mode 100644 index 00000000000..2cd6c93f8f8 --- /dev/null +++ b/changelog/unreleased/bugfix-sharedwithme-degraded-items.md @@ -0,0 +1,25 @@ +Bugfix: Keep shares visible in sharedWithMe when a resource cannot be statted + +The graph `sharedWithMe` handler resolves each received share by fanning out a per-resource +`Stat` call with a concurrency limit, all sharing the request context. When a `Stat` failed +for any reason (slow or stuck downstream, deleted space, gateway error, deadline exceeded) +the worker logged at debug and returned without emitting a drive item, so the share was +silently omitted from the response and the handler still returned `200 OK` with a partial, +non-deterministic list. A single chronically-slow share could therefore make other, +recently-accepted shares intermittently invisible, and repeated calls returned different +subsets of the user's shares. + +The handler now: + +- bounds each per-share `Stat` with its own timeout derived from the request context, so one + slow resource can no longer consume the deadline shared by all the other shares. The bound + is configurable via `GRAPH_RECEIVED_SHARES_STAT_TIMEOUT` (default `10s`); +- returns a degraded drive item built from the data already present in the share record + (ids, permissions, grantees, timestamps, mountpoint name) when the resource cannot be statted + due to a transient or indeterminate failure (timeout, slow or unavailable downstream), so the + share stays visible instead of intermittently disappearing. A genuinely missing resource or + revoked access (for example after the sharer was deleted) still drops the share, as before; +- logs the dropped/degraded shares at warning level with a per-request count for operator + visibility. + +https://github.com/owncloud/ocis/pull/12430 diff --git a/services/graph/pkg/config/config.go b/services/graph/pkg/config/config.go index 45149b8f762..dce3e2b9753 100644 --- a/services/graph/pkg/config/config.go +++ b/services/graph/pkg/config/config.go @@ -34,6 +34,8 @@ type Config struct { UnifiedRoles UnifiedRoles `yaml:"unified_roles"` MaxConcurrency int `yaml:"max_concurrency" env:"OCIS_MAX_CONCURRENCY;GRAPH_MAX_CONCURRENCY" desc:"The maximum number of concurrent requests the service will handle." introductionVersion:"7.0.0"` + ReceivedSharesStatTimeout time.Duration `yaml:"received_shares_stat_timeout" env:"GRAPH_RECEIVED_SHARES_STAT_TIMEOUT" desc:"The maximum duration to wait for the storage to respond while resolving a single received share's resource when listing 'sharedWithMe'. Bounding each resource lookup individually prevents one slow or unreachable resource from consuming the request deadline shared by all the other shares. A share whose resource cannot be statted within this time is still listed as a degraded item instead of being dropped. Defaults to '10s'. See the Environment Variable Types description for more details." introductionVersion:"NEXT"` + Keycloak Keycloak `yaml:"keycloak"` ServiceAccount ServiceAccount `yaml:"service_account"` MultiInstance MultiInstanceConfig `yaml:"multi_instance"` diff --git a/services/graph/pkg/config/defaults/defaultconfig.go b/services/graph/pkg/config/defaults/defaultconfig.go index dea01ac0dcb..6914aa5df0e 100644 --- a/services/graph/pkg/config/defaults/defaultconfig.go +++ b/services/graph/pkg/config/defaults/defaultconfig.go @@ -133,7 +133,8 @@ func DefaultConfig() *config.Config { Cluster: "ocis-cluster", EnableTLS: false, }, - MaxConcurrency: 20, + MaxConcurrency: 20, + ReceivedSharesStatTimeout: 10 * time.Second, UnifiedRoles: config.UnifiedRoles{ AvailableRoles: nil, // will be populated with defaults in EnsureDefaults }, diff --git a/services/graph/pkg/service/v0/base.go b/services/graph/pkg/service/v0/base.go index 3c315b5d9dc..7ed98730801 100644 --- a/services/graph/pkg/service/v0/base.go +++ b/services/graph/pkg/service/v0/base.go @@ -87,7 +87,7 @@ func (g BaseGraphService) CS3ReceivedSharesToDriveItems(ctx context.Context, rec } availableRoles := unifiedrole.GetRoles(unifiedrole.RoleFilterIDs(g.config.UnifiedRoles.AvailableRoles...)) - return cs3ReceivedSharesToDriveItems(ctx, g.logger, gatewayClient, g.identityCache, receivedShares, availableRoles) + return cs3ReceivedSharesToDriveItems(ctx, g.logger, gatewayClient, g.identityCache, receivedShares, availableRoles, g.config.ReceivedSharesStatTimeout) } func (g BaseGraphService) CS3ReceivedOCMSharesToDriveItems(ctx context.Context, receivedShares []*ocm.ReceivedShare) ([]libregraph.DriveItem, error) { diff --git a/services/graph/pkg/service/v0/sharedwithme.go b/services/graph/pkg/service/v0/sharedwithme.go index 0a51d8b0880..24cc44d749d 100644 --- a/services/graph/pkg/service/v0/sharedwithme.go +++ b/services/graph/pkg/service/v0/sharedwithme.go @@ -41,7 +41,7 @@ func (g Graph) listSharedWithMe(ctx context.Context) ([]libregraph.DriveItem, er return nil, err } availableRoles := unifiedrole.GetRoles(unifiedrole.RoleFilterIDs(g.config.UnifiedRoles.AvailableRoles...)) - driveItems, err := cs3ReceivedSharesToDriveItems(ctx, g.logger, gatewayClient, g.identityCache, listReceivedSharesResponse.GetShares(), availableRoles) + driveItems, err := cs3ReceivedSharesToDriveItems(ctx, g.logger, gatewayClient, g.identityCache, listReceivedSharesResponse.GetShares(), availableRoles, g.config.ReceivedSharesStatTimeout) if err != nil { g.logger.Error().Err(err).Msg("could not convert received shares to drive items") return nil, err diff --git a/services/graph/pkg/service/v0/sharedwithme_test.go b/services/graph/pkg/service/v0/sharedwithme_test.go index 31011d1fc43..63a0f13b858 100644 --- a/services/graph/pkg/service/v0/sharedwithme_test.go +++ b/services/graph/pkg/service/v0/sharedwithme_test.go @@ -376,6 +376,157 @@ var _ = Describe("SharedWithMe", func() { Expect(jsonData.Get("id").String()).To(Equal(getUserResponseShareCreator.User.Id.OpaqueId)) }) + It("returns a degraded drive item when a share's resource stat times out", func() { + // a second share, pointing at a different resource, whose Stat times out (transport error) + brokenShare := &collaborationv1beta1.ReceivedShare{ + Share: &collaborationv1beta1.Share{ + ResourceId: toResourceID("7$8!9"), + Id: &collaborationv1beta1.ShareId{ + OpaqueId: "broken:share:id", + }, + Permissions: &collaborationv1beta1.SharePermissions{ + Permissions: roleconversions.NewViewerRole().CS3ResourcePermissions(), + }, + Creator: getUserResponseShareCreator.User.Id, + Ctime: utils.TSNow(), + }, + MountPoint: &providerv1beta1.Reference{Path: "broken folder"}, + State: collaborationv1beta1.ShareState_SHARE_STATE_ACCEPTED, + } + listReceivedSharesResponse.Shares = append(listReceivedSharesResponse.Shares, brokenShare) + + // reset and re-register the gateway expectations so Stat fails for the + // broken share's resource but succeeds for the others. + gatewayClient.ExpectedCalls = nil + gatewayClient.On("GetUser", mock.Anything, mock.Anything).Return(getUserResponseDefault, nil) + gatewayClient.On("ListReceivedShares", mock.Anything, mock.Anything).Return(listReceivedSharesResponse, nil) + gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(func(_ context.Context, r *providerv1beta1.StatRequest, _ ...grpc.CallOption) (*providerv1beta1.StatResponse, error) { + if r.Ref.ResourceId == brokenShare.Share.ResourceId { + return nil, context.DeadlineExceeded + } + return &providerv1beta1.StatResponse{ + Status: status.NewOK(ctx), + Info: &providerv1beta1.ResourceInfo{ + Id: r.Ref.ResourceId, + Type: providerv1beta1.ResourceType_RESOURCE_TYPE_CONTAINER, + }, + }, nil + }) + + svc.ListSharedWithMe( + tape, + httptest.NewRequest(http.MethodGet, "/graph/v1beta1/me/drive/sharedWithMe", nil), + ) + + driveItems := libregraph.CollectionOfDriveItems{} + err := json.Unmarshal(tape.Body.Bytes(), &driveItems) + Expect(err).To(BeNil()) + + // both shares must be present: the broken one is returned as a degraded + // item built from the share record, not silently dropped. + Expect(len(driveItems.Value)).To(Equal(2)) + + var remoteIDs []string + for _, di := range driveItems.GetValue() { + ri := di.GetRemoteItem() + remoteIDs = append(remoteIDs, ri.GetId()) + } + Expect(remoteIDs).To(ContainElement(storagespace.FormatResourceID(brokenShare.Share.ResourceId))) + }) + + It("bounds the per-share Stat with the configured GRAPH_RECEIVED_SHARES_STAT_TIMEOUT", func() { + // Use a value distinct from the 10s default so we can tell the + // configured timeout (not the default) is the one applied. The service + // holds cfg by pointer, so setting it here is observed by the handler. + cfg.ReceivedSharesStatTimeout = 3 * time.Second + + var statDeadline time.Time + var statHadDeadline bool + gatewayClient.ExpectedCalls = nil + gatewayClient.On("GetUser", mock.Anything, mock.Anything).Return(getUserResponseDefault, nil) + gatewayClient.On("ListReceivedShares", mock.Anything, mock.Anything).Return(listReceivedSharesResponse, nil) + gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(func(statCtx context.Context, r *providerv1beta1.StatRequest, _ ...grpc.CallOption) (*providerv1beta1.StatResponse, error) { + // the worker writes these before returning; cs3ReceivedSharesToDriveItems + // only returns after group.Wait(), so reading them after the handler + // call is race-free. + statDeadline, statHadDeadline = statCtx.Deadline() + return &providerv1beta1.StatResponse{ + Status: status.NewOK(ctx), + Info: &providerv1beta1.ResourceInfo{ + Id: r.Ref.ResourceId, + Type: providerv1beta1.ResourceType_RESOURCE_TYPE_CONTAINER, + }, + }, nil + }) + + svc.ListSharedWithMe( + tape, + httptest.NewRequest(http.MethodGet, "/graph/v1beta1/me/drive/sharedWithMe", nil), + ) + + Expect(tape.Code).To(Equal(http.StatusOK)) + // the per-share Stat must carry a deadline derived from the configured + // timeout: never above the configured 3s, and clearly below the 10s default. + Expect(statHadDeadline).To(BeTrue()) + Expect(time.Until(statDeadline)).To(BeNumerically("<=", 3*time.Second)) + Expect(time.Until(statDeadline)).To(BeNumerically(">", 2*time.Second)) + }) + + It("drops a share when the storage returns an error for its resource (e.g. the sharer was deleted)", func() { + // a second share whose resource the storage cannot serve (definitive status error) must not be listed + goneShare := &collaborationv1beta1.ReceivedShare{ + Share: &collaborationv1beta1.Share{ + ResourceId: toResourceID("7$8!9"), + Id: &collaborationv1beta1.ShareId{ + OpaqueId: "gone:share:id", + }, + Permissions: &collaborationv1beta1.SharePermissions{ + Permissions: roleconversions.NewViewerRole().CS3ResourcePermissions(), + }, + Creator: getUserResponseShareCreator.User.Id, + Ctime: utils.TSNow(), + }, + MountPoint: &providerv1beta1.Reference{Path: "gone folder"}, + State: collaborationv1beta1.ShareState_SHARE_STATE_ACCEPTED, + } + listReceivedSharesResponse.Shares = append(listReceivedSharesResponse.Shares, goneShare) + + gatewayClient.ExpectedCalls = nil + gatewayClient.On("GetUser", mock.Anything, mock.Anything).Return(getUserResponseDefault, nil) + gatewayClient.On("ListReceivedShares", mock.Anything, mock.Anything).Return(listReceivedSharesResponse, nil) + gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(func(_ context.Context, r *providerv1beta1.StatRequest, _ ...grpc.CallOption) (*providerv1beta1.StatResponse, error) { + if r.Ref.ResourceId == goneShare.Share.ResourceId { + return &providerv1beta1.StatResponse{Status: status.NewInternal(ctx, "node broken after sharer deletion")}, nil + } + return &providerv1beta1.StatResponse{ + Status: status.NewOK(ctx), + Info: &providerv1beta1.ResourceInfo{ + Id: r.Ref.ResourceId, + Type: providerv1beta1.ResourceType_RESOURCE_TYPE_CONTAINER, + }, + }, nil + }) + + svc.ListSharedWithMe( + tape, + httptest.NewRequest(http.MethodGet, "/graph/v1beta1/me/drive/sharedWithMe", nil), + ) + + driveItems := libregraph.CollectionOfDriveItems{} + err := json.Unmarshal(tape.Body.Bytes(), &driveItems) + Expect(err).To(BeNil()) + + // the dead share (resource gone) is dropped; only the healthy share remains + Expect(len(driveItems.Value)).To(Equal(1)) + + var remoteIDs []string + for _, di := range driveItems.GetValue() { + ri := di.GetRemoteItem() + remoteIDs = append(remoteIDs, ri.GetId()) + } + Expect(remoteIDs).ToNot(ContainElement(storagespace.FormatResourceID(goneShare.Share.ResourceId))) + }) + It("returns a single drive item when multiple shares exist for the same resource", func() { anotherShare := &collaborationv1beta1.ReceivedShare{ Share: &collaborationv1beta1.Share{ diff --git a/services/graph/pkg/service/v0/utils.go b/services/graph/pkg/service/v0/utils.go index a326a3bfbbc..139552fe8bb 100644 --- a/services/graph/pkg/service/v0/utils.go +++ b/services/graph/pkg/service/v0/utils.go @@ -8,6 +8,8 @@ import ( "net/http" "path" "reflect" + "sync/atomic" + "time" gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1" cs3User "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" @@ -170,18 +172,39 @@ func identitySetToSpacePermissionID(identitySet libregraph.SharePointIdentitySet return id } +// _receivedShareStatTimeout is the default bound for how long the resource Stat +// for a single received share may take. It is used when the configured +// GRAPH_RECEIVED_SHARES_STAT_TIMEOUT is not set (or non-positive). Without a +// per-share bound, one slow or stuck downstream resource consumes the whole +// request deadline budget, which causes the other shares to be dropped from the +// sharedWithMe listing (and the request to occasionally 502). Keeping it small +// relative to a typical request deadline lets one bad share fail fast without +// affecting the visibility of the others. +const _receivedShareStatTimeout = 10 * time.Second + func cs3ReceivedSharesToDriveItems(ctx context.Context, logger *log.Logger, gatewayClient gateway.GatewayAPIClient, identityCache identity.IdentityCache, receivedShares []*collaboration.ReceivedShare, availableRoles []*libregraph.UnifiedRoleDefinition, + statTimeout time.Duration, ) ([]libregraph.DriveItem, error) { + // Fall back to the default when unconfigured: a non-positive timeout would + // make context.WithTimeout cancel immediately and drop every share. + if statTimeout <= 0 { + statTimeout = _receivedShareStatTimeout + } + group := new(errgroup.Group) // Set max concurrency group.SetLimit(10) + // number of shares that could not be fully resolved and were returned as a + // degraded drive item built from the share record alone. + var degradedShares atomic.Int64 + receivedSharesByResourceID := make(map[string][]*collaboration.ReceivedShare, len(receivedShares)) for _, receivedShare := range receivedShares { if receivedShare == nil { @@ -197,18 +220,39 @@ func cs3ReceivedSharesToDriveItems(ctx context.Context, receivedShares := receivedSharesForResource group.Go(func() error { - var err error // redeclare - shareStat, err := gatewayClient.Stat(ctx, &storageprovider.StatRequest{ + // Bound the per-share Stat so one slow/stuck resource cannot consume + // the request deadline shared by all the other shares. + statCtx, cancel := context.WithTimeout(ctx, statTimeout) + defer cancel() + shareStat, err := gatewayClient.Stat(statCtx, &storageprovider.StatRequest{ Ref: &storageprovider.Reference{ ResourceId: receivedShares[0].GetShare().GetResourceId(), }, }) - if err := errorcode.FromCS3Status(shareStat.GetStatus(), err); err != nil { - logger.Debug().Err(err). + if err != nil { + // The storage could not be reached in time (per-share timeout, + // cancellation, or an unavailable downstream). The resource most + // likely still exists, so keep the share visible as a degraded item + // built from the share record instead of dropping it: a single slow + // share must neither vanish nor take the other shares down with it. + logger.Warn().Err(err). Str("shareid", receivedShares[0].GetShare().GetId().GetOpaqueId()). Str("resourceid", storagespace.FormatResourceID(receivedShares[0].GetShare().GetResourceId())). - Msg("could not stat received share, skipping") + Msg("could not stat received share, returning a degraded drive item") + degradedShares.Add(1) + ch <- *buildDegradedDriveItemFromReceivedShares(ctx, logger, identityCache, receivedShares, availableRoles) + return nil + } + + if statErr := errorcode.FromCS3Status(shareStat.GetStatus(), nil); statErr != nil { + // The storage answered with a definitive error (resource gone, + // access revoked, or a broken node, e.g. after the sharer was + // deleted). The share is dead and must not be listed. + logger.Debug().Err(statErr). + Str("shareid", receivedShares[0].GetShare().GetId().GetOpaqueId()). + Str("resourceid", storagespace.FormatResourceID(receivedShares[0].GetShare().GetResourceId())). + Msg("could not stat received share, skipping (resource unavailable)") return nil } @@ -348,9 +392,68 @@ func cs3ReceivedSharesToDriveItems(ctx context.Context, driveItems = append(driveItems, di) } + if n := degradedShares.Load(); n > 0 { + logger.Warn(). + Int64("degraded", n). + Int("total", len(receivedSharesByResourceID)). + Msg("some received shares could not be fully resolved and were returned as degraded drive items") + } + return driveItems, err } +// buildDegradedDriveItemFromReceivedShares constructs a DriveItem for a set of +// received shares pointing at the same resource when that resource could not be +// statted. It exposes the data already contained in the share records (ids, +// permissions, grantees, timestamps, mountpoint name) so the share stays +// visible in the sharedWithMe listing instead of being silently dropped. +// Properties that are only known from a successful Stat (size, etag, mime type, +// owner, file/folder type) are intentionally left unset. It never returns an +// error: if even the degraded build fails it falls back to a minimal item that +// still carries the share identity. +func buildDegradedDriveItemFromReceivedShares(ctx context.Context, logger *log.Logger, + identityCache identity.IdentityCache, receivedShares []*collaboration.ReceivedShare, + availableRoles []*libregraph.UnifiedRoleDefinition) *libregraph.DriveItem { + + driveItem, err := fillDriveItemPropertiesFromReceivedShare(ctx, logger, identityCache, receivedShares, nil, availableRoles) + if err != nil { + logger.Warn().Err(err). + Str("shareid", receivedShares[0].GetShare().GetId().GetOpaqueId()). + Msg("could not build degraded drive item, returning a minimal item") + driveItem = libregraph.NewDriveItem() + driveItem.SetId(storagespace.FormatResourceID(&storageprovider.ResourceId{ + StorageId: utils.ShareStorageProviderID, + OpaqueId: receivedShares[0].GetShare().GetId().GetOpaqueId(), + SpaceId: utils.ShareStorageSpaceID, + })) + driveItem.RemoteItem = libregraph.NewRemoteItem() + } + + // the item lives in the virtual share jail, same as the fully-resolved item + driveItem.ParentReference = libregraph.NewItemReference() + driveItem.ParentReference.SetDriveType(_spaceTypeVirtual) + driveItem.ParentReference.SetDriveId(storagespace.FormatStorageID(utils.ShareStorageProviderID, utils.ShareStorageSpaceID)) + driveItem.ParentReference.SetId(storagespace.FormatResourceID(&storageprovider.ResourceId{ + StorageId: utils.ShareStorageProviderID, + OpaqueId: utils.ShareStorageSpaceID, + SpaceId: utils.ShareStorageSpaceID, + })) + + if rid := receivedShares[0].GetShare().GetResourceId(); rid != nil { + driveItem.RemoteItem.SetId(storagespace.FormatResourceID(rid)) + driveItem.RemoteItem.SpaceId = libregraph.PtrString(storagespace.FormatStorageID(rid.GetStorageId(), rid.GetSpaceId())) + } + + // fall back to the mountpoint name when the resource name is unknown + if driveItem.GetName() == "" { + if name := receivedShares[0].GetMountPoint().GetPath(); name != "" { + driveItem.SetName(name) + } + } + + return driveItem +} + func fillDriveItemPropertiesFromReceivedShare(ctx context.Context, logger *log.Logger, identityCache identity.IdentityCache, receivedShares []*collaboration.ReceivedShare, resourceInfo *storageprovider.ResourceInfo, availableRoles []*libregraph.UnifiedRoleDefinition) (*libregraph.DriveItem, error) { @@ -443,26 +546,36 @@ func cs3ReceivedShareToLibreGraphPermissions(ctx context.Context, logger *log.Lo } if permissionSet := receivedShare.GetShare().GetPermissions().GetPermissions(); permissionSet != nil { - condition, err := roleConditionForResourceType(resourceInfo) - if err != nil { - return nil, err - } + // resourceInfo is nil for a degraded item, i.e. when the underlying + // resource could not be statted. The resource type, and therefore the + // unified role, cannot be determined in that case, so expose the raw + // actions instead of failing the whole listing. + if resourceInfo == nil { + if actions := unifiedrole.CS3ResourcePermissionsToLibregraphActions(permissionSet); len(actions) > 0 { + permission.SetLibreGraphPermissionsActions(actions) + } + } else { + condition, err := roleConditionForResourceType(resourceInfo) + if err != nil { + return nil, err + } - role := unifiedrole.CS3ResourcePermissionsToRole( - availableRoles, - permissionSet, - condition, - false, - ) - if role != nil { - permission.SetRoles([]string{role.GetId()}) - } + role := unifiedrole.CS3ResourcePermissionsToRole( + availableRoles, + permissionSet, + condition, + false, + ) + if role != nil { + permission.SetRoles([]string{role.GetId()}) + } - actions := unifiedrole.CS3ResourcePermissionsToLibregraphActions(permissionSet) + actions := unifiedrole.CS3ResourcePermissionsToLibregraphActions(permissionSet) - // actions only make sense if no role is set - if role == nil && len(actions) > 0 { - permission.SetLibreGraphPermissionsActions(actions) + // actions only make sense if no role is set + if role == nil && len(actions) > 0 { + permission.SetLibreGraphPermissionsActions(actions) + } } } switch grantee := receivedShare.GetShare().GetGrantee(); {