diff --git a/go.mod b/go.mod index 04c6c24ff5..5c4585c48e 100644 --- a/go.mod +++ b/go.mod @@ -67,7 +67,7 @@ require ( github.com/open-policy-agent/opa v1.21.1 github.com/opencloud-eu/icap-client v0.0.0-20250930132611-28a2afe62d89 github.com/opencloud-eu/libre-graph-api-go v1.0.9-0.20261016073229-17ed3d5dd346 - github.com/opencloud-eu/reva/v2 v2.52.2 + github.com/opencloud-eu/reva/v2 v2.52.3-0.20261113144838-03685668969d github.com/opensearch-project/opensearch-go/v4 v4.7.3 github.com/orcaman/concurrent-map v1.0.0 github.com/pkg/errors v0.9.1 diff --git a/go.sum b/go.sum index fd7dbfade8..034d8c0409 100644 --- a/go.sum +++ b/go.sum @@ -759,8 +759,8 @@ github.com/opencloud-eu/icap-client v0.0.0-20250930132611-28a2afe62d89 h1:W1ms+l github.com/opencloud-eu/icap-client v0.0.0-20250930132611-28a2afe62d89/go.mod h1:vigJkNss1N2QEceCuNw/ullDehncuJNFB6mEnzfq9UI= github.com/opencloud-eu/libre-graph-api-go v1.0.9-0.20261016073229-17ed3d5dd346 h1:3ptbiFhSK4fzY/rC3idcYUveiwepMoOov1sBpc7Rg3k= github.com/opencloud-eu/libre-graph-api-go v1.0.9-0.20261016073229-17ed3d5dd346/go.mod h1:lTM8JeGblNpoMySTW7Lui2+c5TTLI95mwxtdUIHHrhU= -github.com/opencloud-eu/reva/v2 v2.52.2 h1:uSYHhzX9hv911ciAyCVShg99cUoudkmFu+WVK2G85eI= -github.com/opencloud-eu/reva/v2 v2.52.2/go.mod h1:jqg3kpCQTwagdcnu/D+resnrnNzSg6cjAQ/Wv4fmvBI= +github.com/opencloud-eu/reva/v2 v2.52.3-0.20261113144838-03685668969d h1:U9B6MvPDbNWwoOUHCPUO1GwxL/n1TbE2Tlomo+P0Qp4= +github.com/opencloud-eu/reva/v2 v2.52.3-0.20261113144838-03685668969d/go.mod h1:nKOQFFHQZiBFiiXBqEIc99giHQ/Pe0XYf5cztJhZDYw= github.com/opencloud-eu/secure v0.0.0-20260312082735-b6f5cb2244e4 h1:l2oB/RctH+t8r7QBj5p8thfEHCM/jF35aAY3WQ3hADI= github.com/opencloud-eu/secure v0.0.0-20260312082735-b6f5cb2244e4/go.mod h1:BmF5hyM6tXczk3MpQkFf1hpKSRqCyhqcbiQtiAF7+40= github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= diff --git a/services/frontend/README.md b/services/frontend/README.md index 65b09be7a9..c493388722 100644 --- a/services/frontend/README.md +++ b/services/frontend/README.md @@ -134,3 +134,11 @@ For public accessible writable shares, a password can be enforced. To change the Note that changing this environment variable only makes sense if\ `OC_SHARING_PUBLIC_SHARE_MUST_HAVE_PASSWORD`\ is set to `false`. + +## Server Managed Spaces + +The `frontend` service can announce that the membership of spaces is managed by the server instead of by users. To enable this, set the following environment variable to `true`: + +`OC_CLAIM_MANAGED_SPACES_ENABLED` + +When enabled, the `spaces` capability contains `server_managed: true`. Clients like the web UI evaluate this capability and block adding or removing users to or from spaces. diff --git a/services/frontend/pkg/config/config.go b/services/frontend/pkg/config/config.go index bceda65970..1bc358f4d2 100644 --- a/services/frontend/pkg/config/config.go +++ b/services/frontend/pkg/config/config.go @@ -61,6 +61,8 @@ type Config struct { ConfigurableNotifications bool `yaml:"configurable_notifications" env:"FRONTEND_CONFIGURABLE_NOTIFICATIONS" desc:"Allow configuring notifications via web client." introductionVersion:"1.0.0"` + ServerManagedSpaces bool `yaml:"server_managed_spaces" env:"OC_CLAIM_MANAGED_SPACES_ENABLED" desc:"Mark spaces as managed by the server. Clients like the web UI then block adding or removing users to or from spaces. See the text description for more details." introductionVersion:"%%NEXT%%"` + Groupware Groupware `yaml:"groupware"` Context context.Context `yaml:"-"` diff --git a/services/frontend/pkg/revaconfig/config.go b/services/frontend/pkg/revaconfig/config.go index 537b14524c..989661adce 100644 --- a/services/frontend/pkg/revaconfig/config.go +++ b/services/frontend/pkg/revaconfig/config.go @@ -296,12 +296,13 @@ func FrontendConfigFromStruct(cfg *config.Config, logger log.Logger) (map[string }, }, "spaces": map[string]any{ - "version": "1.0.0", - "enabled": true, - "projects": true, - "share_jail": true, - "max_quota": cfg.MaxQuota, - "default_quota": parseQuota(cfg.DefaultQuota), + "version": "1.0.0", + "enabled": true, + "projects": true, + "share_jail": true, + "max_quota": cfg.MaxQuota, + "default_quota": parseQuota(cfg.DefaultQuota), + "server_managed": cfg.ServerManagedSpaces, }, "theme": capabilities.Default().Theme, "search": map[string]any{ diff --git a/services/frontend/pkg/revaconfig/config_test.go b/services/frontend/pkg/revaconfig/config_test.go index fbaf731150..df8656e4d8 100644 --- a/services/frontend/pkg/revaconfig/config_test.go +++ b/services/frontend/pkg/revaconfig/config_test.go @@ -24,6 +24,20 @@ func TestContentSearchCapabilityFollowsFullTextSearch(t *testing.T) { } } +func TestServerManagedCapabilityFollowsServerManagedSpaces(t *testing.T) { + for _, enabled := range []bool{true, false} { + cfg := defaults.FullDefaultConfig() + cfg.Commons = &shared.Commons{} + cfg.ServerManagedSpaces = enabled + + rcfg, err := FrontendConfigFromStruct(cfg, log.NopLogger()) + require.NoError(t, err) + + got := dig(t, rcfg, "http", "services", "ocs", "capabilities", "capabilities", "spaces")["server_managed"] + require.Equal(t, enabled, got) + } +} + func dig(t *testing.T, m map[string]any, keys ...string) map[string]any { t.Helper() for _, k := range keys { diff --git a/services/graph/mocks/drive_item_permissions_provider.go b/services/graph/mocks/drive_item_permissions_provider.go index 082ce69b9e..71b9e25cfb 100644 --- a/services/graph/mocks/drive_item_permissions_provider.go +++ b/services/graph/mocks/drive_item_permissions_provider.go @@ -310,6 +310,150 @@ func (_c *DriveItemPermissionsProvider_DeleteSpaceRootPermission_Call) RunAndRet return _c } +// GetPermission provides a mock function for the type DriveItemPermissionsProvider +func (_mock *DriveItemPermissionsProvider) GetPermission(ctx context.Context, itemID *providerv1beta1.ResourceId, permissionID string) (libregraph.Permission, error) { + ret := _mock.Called(ctx, itemID, permissionID) + + if len(ret) == 0 { + panic("no return value specified for GetPermission") + } + + var r0 libregraph.Permission + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, *providerv1beta1.ResourceId, string) (libregraph.Permission, error)); ok { + return returnFunc(ctx, itemID, permissionID) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, *providerv1beta1.ResourceId, string) libregraph.Permission); ok { + r0 = returnFunc(ctx, itemID, permissionID) + } else { + r0 = ret.Get(0).(libregraph.Permission) + } + if returnFunc, ok := ret.Get(1).(func(context.Context, *providerv1beta1.ResourceId, string) error); ok { + r1 = returnFunc(ctx, itemID, permissionID) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// DriveItemPermissionsProvider_GetPermission_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetPermission' +type DriveItemPermissionsProvider_GetPermission_Call struct { + *mock.Call +} + +// GetPermission is a helper method to define mock.On call +// - ctx context.Context +// - itemID *providerv1beta1.ResourceId +// - permissionID string +func (_e *DriveItemPermissionsProvider_Expecter) GetPermission(ctx any, itemID any, permissionID any) *DriveItemPermissionsProvider_GetPermission_Call { + return &DriveItemPermissionsProvider_GetPermission_Call{Call: _e.mock.On("GetPermission", ctx, itemID, permissionID)} +} + +func (_c *DriveItemPermissionsProvider_GetPermission_Call) Run(run func(ctx context.Context, itemID *providerv1beta1.ResourceId, permissionID string)) *DriveItemPermissionsProvider_GetPermission_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *providerv1beta1.ResourceId + if args[1] != nil { + arg1 = args[1].(*providerv1beta1.ResourceId) + } + var arg2 string + if args[2] != nil { + arg2 = args[2].(string) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *DriveItemPermissionsProvider_GetPermission_Call) Return(permission libregraph.Permission, err error) *DriveItemPermissionsProvider_GetPermission_Call { + _c.Call.Return(permission, err) + return _c +} + +func (_c *DriveItemPermissionsProvider_GetPermission_Call) RunAndReturn(run func(ctx context.Context, itemID *providerv1beta1.ResourceId, permissionID string) (libregraph.Permission, error)) *DriveItemPermissionsProvider_GetPermission_Call { + _c.Call.Return(run) + return _c +} + +// GetSpaceRootPermission provides a mock function for the type DriveItemPermissionsProvider +func (_mock *DriveItemPermissionsProvider) GetSpaceRootPermission(ctx context.Context, driveID *providerv1beta1.ResourceId, permissionID string) (libregraph.Permission, error) { + ret := _mock.Called(ctx, driveID, permissionID) + + if len(ret) == 0 { + panic("no return value specified for GetSpaceRootPermission") + } + + var r0 libregraph.Permission + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, *providerv1beta1.ResourceId, string) (libregraph.Permission, error)); ok { + return returnFunc(ctx, driveID, permissionID) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, *providerv1beta1.ResourceId, string) libregraph.Permission); ok { + r0 = returnFunc(ctx, driveID, permissionID) + } else { + r0 = ret.Get(0).(libregraph.Permission) + } + if returnFunc, ok := ret.Get(1).(func(context.Context, *providerv1beta1.ResourceId, string) error); ok { + r1 = returnFunc(ctx, driveID, permissionID) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// DriveItemPermissionsProvider_GetSpaceRootPermission_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetSpaceRootPermission' +type DriveItemPermissionsProvider_GetSpaceRootPermission_Call struct { + *mock.Call +} + +// GetSpaceRootPermission is a helper method to define mock.On call +// - ctx context.Context +// - driveID *providerv1beta1.ResourceId +// - permissionID string +func (_e *DriveItemPermissionsProvider_Expecter) GetSpaceRootPermission(ctx any, driveID any, permissionID any) *DriveItemPermissionsProvider_GetSpaceRootPermission_Call { + return &DriveItemPermissionsProvider_GetSpaceRootPermission_Call{Call: _e.mock.On("GetSpaceRootPermission", ctx, driveID, permissionID)} +} + +func (_c *DriveItemPermissionsProvider_GetSpaceRootPermission_Call) Run(run func(ctx context.Context, driveID *providerv1beta1.ResourceId, permissionID string)) *DriveItemPermissionsProvider_GetSpaceRootPermission_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *providerv1beta1.ResourceId + if args[1] != nil { + arg1 = args[1].(*providerv1beta1.ResourceId) + } + var arg2 string + if args[2] != nil { + arg2 = args[2].(string) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *DriveItemPermissionsProvider_GetSpaceRootPermission_Call) Return(permission libregraph.Permission, err error) *DriveItemPermissionsProvider_GetSpaceRootPermission_Call { + _c.Call.Return(permission, err) + return _c +} + +func (_c *DriveItemPermissionsProvider_GetSpaceRootPermission_Call) RunAndReturn(run func(ctx context.Context, driveID *providerv1beta1.ResourceId, permissionID string) (libregraph.Permission, error)) *DriveItemPermissionsProvider_GetSpaceRootPermission_Call { + _c.Call.Return(run) + return _c +} + // Invite provides a mock function for the type DriveItemPermissionsProvider func (_mock *DriveItemPermissionsProvider) Invite(ctx context.Context, resourceId *providerv1beta1.ResourceId, invite libregraph.DriveItemInvite) (libregraph.Permission, error) { ret := _mock.Called(ctx, resourceId, invite) diff --git a/services/graph/pkg/service/v0/api_driveitem_permissions.go b/services/graph/pkg/service/v0/api_driveitem_permissions.go index 7d43726744..c0a3164a67 100644 --- a/services/graph/pkg/service/v0/api_driveitem_permissions.go +++ b/services/graph/pkg/service/v0/api_driveitem_permissions.go @@ -28,6 +28,11 @@ import ( "github.com/opencloud-eu/reva/v2/pkg/share" "github.com/opencloud-eu/reva/v2/pkg/storagespace" "github.com/opencloud-eu/reva/v2/pkg/utils" + "github.com/rs/zerolog" + "go.opentelemetry.io/otel/codes" + semconv "go.opentelemetry.io/otel/semconv/v1.37.0" + "go.opentelemetry.io/otel/trace" + "go.opentelemetry.io/otel/trace/noop" "github.com/opencloud-eu/opencloud/pkg/conversions" "github.com/opencloud-eu/opencloud/pkg/l10n" @@ -46,6 +51,28 @@ const ( parseDriveIDErrMsg = "could not parse driveID" federatedRolesODataFilter = "@libre.graph.permissions.roles.allowedValues/rolePermissions/any(p:contains(p/condition, '@Subject.UserType==\"Federated\"'))" noLinksODataFilter = "grantedToV2 ne ''" + + // _tracerName is the name of the tracer that records the spans of the permission operations + _tracerName = "graph" + + // log keys of the permission operations + _logKeyItemID = "itemID" + _logKeyDriveID = "driveID" + _logKeyPermissionID = "permissionID" + _logKeyPermissionType = "permissionType" + _logKeyRoleID = "roleID" + _logKeyRecipientType = "recipientType" + _logKeySpaceType = "spaceType" + _logKeyUserID = "userID" + _logKeyErrorCode = "errorCode" + _logKeyLookupError = "lookupError" + _logKeyOCMError = "ocmError" + + // recipient types of an invitation + _recipientTypeUser = "user" + _recipientTypeGroup = "group" + _recipientTypeMail = "mail" + _recipientTypeOCM = "ocm" ) // DriveItemPermissionsProvider contains the methods related to handling permissions on drive items @@ -62,11 +89,14 @@ type DriveItemPermissionsProvider interface { CreateSpaceRootLink(ctx context.Context, driveID *storageprovider.ResourceId, createLink libregraph.DriveItemCreateLink) (libregraph.Permission, error) SetPublicLinkPassword(ctx context.Context, driveItemID *storageprovider.ResourceId, permissionID string, password string) (libregraph.Permission, error) SetPublicLinkPasswordOnSpaceRoot(ctx context.Context, driveID *storageprovider.ResourceId, permissionID string, password string) (libregraph.Permission, error) + GetPermission(ctx context.Context, itemID *storageprovider.ResourceId, permissionID string) (libregraph.Permission, error) + GetSpaceRootPermission(ctx context.Context, driveID *storageprovider.ResourceId, permissionID string) (libregraph.Permission, error) } // DriveItemPermissionsService contains the production business logic for everything that relates to permissions on drive items. type DriveItemPermissionsService struct { BaseGraphService + tp trace.TracerProvider } type permissionType int @@ -88,11 +118,14 @@ type ListPermissionsQueryOptions struct { } // NewDriveItemPermissionsService creates a new DriveItemPermissionsService -func NewDriveItemPermissionsService(logger log.Logger, gatewaySelector pool.Selectable[gateway.GatewayAPIClient], identityCache cache.IdentityCache, config *config.Config) (DriveItemPermissionsService, error) { +func NewDriveItemPermissionsService(logger log.Logger, gatewaySelector pool.Selectable[gateway.GatewayAPIClient], identityCache cache.IdentityCache, config *config.Config, tp trace.TracerProvider) (DriveItemPermissionsService, error) { publicBaseURL, err := url.Parse(config.Spaces.WebDavBase) if err != nil { return DriveItemPermissionsService{}, fmt.Errorf("could not parse graph.spaces.webdav_base: %w", err) } + if tp == nil { + tp = noop.NewTracerProvider() + } return DriveItemPermissionsService{ BaseGraphService: BaseGraphService{ logger: &log.Logger{Logger: logger.With().Str("graph api", "DrivesDriveItemService").Logger()}, @@ -102,25 +135,99 @@ func NewDriveItemPermissionsService(logger log.Logger, gatewaySelector pool.Sele availableRoles: unifiedrole.GetRoles(unifiedrole.RoleFilterIDs(config.UnifiedRoles.AvailableRoles...)), publicBaseURL: publicBaseURL, }, + tp: tp, }, nil } +// logLevelForError returns the log level matching the cause of err: +// expected client errors are logged at debug level, everything else at error level. +// Client errors are the codes errorcode.Error.Render maps to a 4xx status. This is a +// default only: call sites that know the operational context better (e.g. a +// NOT_FOUND that is part of a lookup chain) should choose their level explicitly. +func logLevelForError(err error) zerolog.Level { + if e, ok := errorcode.ToError(err); ok { + switch e.GetCode() { + case errorcode.ItemNotFound, errorcode.AccessDenied, errorcode.InvalidRequest, + errorcode.NameAlreadyExists, errorcode.InvalidRange, errorcode.ItemIsLocked, + errorcode.PreconditionFailed, errorcode.NotAllowed: + return zerolog.DebugLevel + } + } + return zerolog.ErrorLevel +} + +// errorCodeForError returns the graph error code err is rendered with. It classifies the failure +// in logs and spans. +func errorCodeForError(err error) string { + if e, ok := errorcode.ToError(err); ok { + return e.GetCode().String() + } + return errorcode.GeneralException.String() +} + +// errorEvent starts a log event for err at the level matching its cause. It carries the error +// code and the error text, so operators see the reason. +func errorEvent(logger *log.Logger, err error) *zerolog.Event { + return logger.WithLevel(logLevelForError(err)).Str(_logKeyErrorCode, errorCodeForError(err)).Err(err) +} + +// fallbackErrorEvent starts a log event for err, the error returned after a fallback attempt that +// failed with otherErr (which may be nil). The level matches the more severe of both causes, so an +// infrastructure failure is not hidden behind the not found of the other attempt. Like errorEvent, +// it carries the code and the text of err; those of otherErr are logged under otherKey+"Code" and +// otherKey. +func fallbackErrorEvent(logger *log.Logger, err, otherErr error, otherKey string) *zerolog.Event { + if otherErr == nil { + return errorEvent(logger, err) + } + level := max(logLevelForError(err), logLevelForError(otherErr)) + return logger.WithLevel(level). + Str(_logKeyErrorCode, errorCodeForError(err)).Err(err). + Str(otherKey+"Code", errorCodeForError(otherErr)).AnErr(otherKey, otherErr) +} + +// endSpan ends span, recording the error code of a failed operation. Like the log level, the span +// status only marks unexpected failures as error. Spans classify the failure by its code only, +// the error text is in the log entry of the same request. +func endSpan(span trace.Span, err error) { + if err != nil { + span.SetAttributes(semconv.ErrorTypeKey.String(errorCodeForError(err))) + setSpanErrorStatus(span, err) + } + span.End() +} + +// setSpanErrorStatus marks span as error when the cause of err is an unexpected failure, with the error +// code as description. Call sites that return a different error than the cause use it to keep the cause +// visible, endSpan never clears the status again. A nil err leaves the status untouched. +func setSpanErrorStatus(span trace.Span, err error) { + if err != nil && logLevelForError(err) == zerolog.ErrorLevel { + span.SetStatus(codes.Error, errorCodeForError(err)) + } +} + // Invite invites a user to a drive item. -func (s DriveItemPermissionsService) Invite(ctx context.Context, resourceId *storageprovider.ResourceId, invite libregraph.DriveItemInvite) (libregraph.Permission, error) { +func (s DriveItemPermissionsService) Invite(ctx context.Context, resourceId *storageprovider.ResourceId, invite libregraph.DriveItemInvite) (_ libregraph.Permission, err error) { + ctx, span := s.tp.Tracer(_tracerName).Start(ctx, "Invite") + defer func() { endSpan(span, err) }() + logger := s.logger.SubloggerWithRequestID(ctx) + tenantId := revactx.ContextMustGetUser(ctx).GetId().GetTenantId() gatewayClient, err := s.gatewaySelector.Next() if err != nil { + errorEvent(&logger, err).Str(_logKeyItemID, storagespace.FormatResourceID(resourceId)).Msg("could not select next gateway client") return libregraph.Permission{}, err } statResponse, err := gatewayClient.Stat(ctx, &storageprovider.StatRequest{Ref: &storageprovider.Reference{ResourceId: resourceId}}) if err := errorcode.FromStat(statResponse, err); err != nil { - s.logger.Warn().Err(err).Interface("stat.res", statResponse).Msg("stat failed") + errorEvent(&logger, err).Str(_logKeyItemID, storagespace.FormatResourceID(resourceId)).Msg("stat failed") return libregraph.Permission{}, err } var condition string if condition, err = roleConditionForResourceType(statResponse.GetInfo()); err != nil { + logger.Debug().Err(err).Str(_logKeyItemID, storagespace.FormatResourceID(resourceId)).Msg("unsupported resource type") return libregraph.Permission{}, err } @@ -128,18 +235,21 @@ func (s DriveItemPermissionsService) Invite(ctx context.Context, resourceId *sto for _, roleID := range invite.GetRoles() { // only allow roles that are enabled in the config if !slices.Contains(s.config.UnifiedRoles.AvailableRoles, roleID) { + logger.Debug().Err(unifiedrole.ErrUnknownRole).Str(_logKeyItemID, storagespace.FormatResourceID(resourceId)).Str(_logKeyRoleID, roleID).Msg("unknown role") return libregraph.Permission{}, unifiedrole.ErrUnknownRole } role, err := unifiedrole.GetRole(unifiedrole.RoleFilterIDs(roleID)) if err != nil { - s.logger.Debug().Err(err).Interface("role", invite.GetRoles()[0]).Msg("unable to convert requested role") + logger.Debug().Err(err).Str(_logKeyItemID, storagespace.FormatResourceID(resourceId)).Str(_logKeyRoleID, roleID).Msg("unable to convert requested role") return libregraph.Permission{}, err } allowedResourceActions := unifiedrole.GetAllowedResourceActions(role, condition) if len(allowedResourceActions) == 0 && role.GetId() != unifiedrole.UnifiedRoleDeniedID { - return libregraph.Permission{}, errorcode.New(errorcode.InvalidRequest, "role not applicable to this resource") + notApplicableErr := errorcode.New(errorcode.InvalidRequest, "role not applicable to this resource") + logger.Debug().Err(notApplicableErr).Str(_logKeyItemID, storagespace.FormatResourceID(resourceId)).Str(_logKeyRoleID, roleID).Msg("role not applicable to this resource") + return libregraph.Permission{}, notApplicableErr } unifiedRolePermissions = append(unifiedRolePermissions, conversions.ToPointerSlice(role.GetRolePermissions())...) @@ -165,7 +275,9 @@ func (s DriveItemPermissionsService) Invite(ctx context.Context, resourceId *sto var cTime *types.Timestamp if email := driveRecipient.GetEmail(); email != "" { if s.config.Commons == nil || !s.config.Commons.EnableGuestLinks { - return libregraph.Permission{}, errorcode.New(errorcode.NotSupported, "sharing with mail recipients is not enabled") + mailErr := errorcode.New(errorcode.NotSupported, "sharing with mail recipients is not enabled") + logger.Debug().Err(mailErr).Str(_logKeyItemID, storagespace.FormatResourceID(resourceId)).Msg("sharing with mail recipients is not enabled") + return libregraph.Permission{}, mailErr } createShareRequest := createShareRequestToMail(email, statResponse.GetInfo(), cs3ResourcePermissions) @@ -175,7 +287,7 @@ func (s DriveItemPermissionsService) Invite(ctx context.Context, resourceId *sto createShareResponse, err := gatewayClient.CreateShare(ctx, createShareRequest) if err := errorcode.FromCS3Status(createShareResponse.GetStatus(), err); err != nil { - s.logger.Debug().Err(err).Msg("share creation failed") + errorEvent(&logger, err).Str(_logKeyItemID, storagespace.FormatResourceID(resourceId)).Str(_logKeyRecipientType, _recipientTypeMail).Msg("share creation failed") return libregraph.Permission{}, err } shareid = createShareResponse.GetShare().GetId().GetOpaqueId() @@ -185,7 +297,7 @@ func (s DriveItemPermissionsService) Invite(ctx context.Context, resourceId *sto // the share provider stores the guest's mail address in its canonical form guestIdentity, err := cs3UserIdToIdentity(ctx, s.identityCache, createShareResponse.GetShare().GetGrantee().GetUserId()) if err != nil { - s.logger.Debug().Err(err).Msg("failed to convert guest user id to identity") + errorEvent(&logger, err).Str(_logKeyItemID, storagespace.FormatResourceID(resourceId)).Str(_logKeyRecipientType, _recipientTypeMail).Msg("failed to convert guest user id to identity") return libregraph.Permission{}, err } @@ -195,10 +307,11 @@ func (s DriveItemPermissionsService) Invite(ctx context.Context, resourceId *sto } else { switch driveRecipient.GetLibreGraphRecipientType() { - case "group": + case _recipientTypeGroup: group, err := s.identityCache.GetGroup(ctx, objectID) if err != nil { - s.logger.Debug().Err(err).Interface("groupId", objectID).Msg("failed group lookup") + errorEvent(&logger, err).Str(_logKeyItemID, storagespace.FormatResourceID(resourceId)).Str(_logKeyRecipientType, _recipientTypeGroup).Msg("recipient lookup failed") + setSpanErrorStatus(span, err) return libregraph.Permission{}, errorcode.New(errorcode.InvalidRequest, err.Error()) } permission.GrantedToV2 = &libregraph.SharePointIdentitySet{ @@ -213,7 +326,7 @@ func (s DriveItemPermissionsService) Invite(ctx context.Context, resourceId *sto } createShareResponse, err := gatewayClient.CreateShare(ctx, createShareRequest) if err := errorcode.FromCS3Status(createShareResponse.GetStatus(), err); err != nil { - s.logger.Debug().Err(err).Msg("share creation failed") + errorEvent(&logger, err).Str(_logKeyItemID, storagespace.FormatResourceID(resourceId)).Str(_logKeyRecipientType, _recipientTypeGroup).Msg("share creation failed") return libregraph.Permission{}, err } shareid = createShareResponse.GetShare().GetId().GetOpaqueId() @@ -224,11 +337,14 @@ func (s DriveItemPermissionsService) Invite(ctx context.Context, resourceId *sto if errors.Is(err, identity.ErrNotFound) && s.config.IncludeOCMSharees { user, err = s.identityCache.GetAcceptedCS3User(ctx, objectID) if err == nil && IsSpaceRoot(statResponse.GetInfo().GetId()) { - return libregraph.Permission{}, errorcode.New(errorcode.InvalidRequest, "federated user can not become a space member") + federatedErr := errorcode.New(errorcode.InvalidRequest, "federated user can not become a space member") + logger.Debug().Err(federatedErr).Str(_logKeyItemID, storagespace.FormatResourceID(resourceId)).Msg("federated user can not become a space member") + return libregraph.Permission{}, federatedErr } } if err != nil { - s.logger.Debug().Err(err).Interface("userId", objectID).Msg("failed user lookup") + errorEvent(&logger, err).Str(_logKeyItemID, storagespace.FormatResourceID(resourceId)).Str(_logKeyRecipientType, _recipientTypeUser).Msg("recipient lookup failed") + setSpanErrorStatus(span, err) return libregraph.Permission{}, errorcode.New(errorcode.InvalidRequest, err.Error()) } permission.GrantedToV2 = &libregraph.SharePointIdentitySet{ @@ -244,7 +360,7 @@ func (s DriveItemPermissionsService) Invite(ctx context.Context, resourceId *sto Domain: user.GetId().GetIdp(), }) if err = errorcode.FromCS3Status(providerInfoResp.GetStatus(), err); err != nil { - s.logger.Error().Err(err).Msg("getting provider info failed") + errorEvent(&logger, err).Str(_logKeyItemID, storagespace.FormatResourceID(resourceId)).Str(_logKeyRecipientType, _recipientTypeOCM).Msg("getting provider info failed") return libregraph.Permission{}, err } @@ -254,7 +370,7 @@ func (s DriveItemPermissionsService) Invite(ctx context.Context, resourceId *sto } createShareResponse, err := gatewayClient.CreateOCMShare(ctx, createShareRequest) if err = errorcode.FromCS3Status(createShareResponse.GetStatus(), err); err != nil { - s.logger.Error().Err(err).Msg("share creation failed") + errorEvent(&logger, err).Str(_logKeyItemID, storagespace.FormatResourceID(resourceId)).Str(_logKeyRecipientType, _recipientTypeOCM).Msg("share creation failed") return libregraph.Permission{}, err } shareid = createShareResponse.GetShare().GetId().GetOpaqueId() @@ -267,7 +383,7 @@ func (s DriveItemPermissionsService) Invite(ctx context.Context, resourceId *sto } createShareResponse, err := gatewayClient.CreateShare(ctx, createShareRequest) if err = errorcode.FromCS3Status(createShareResponse.GetStatus(), err); err != nil { - s.logger.Error().Err(err).Msg("share creation failed") + errorEvent(&logger, err).Str(_logKeyItemID, storagespace.FormatResourceID(resourceId)).Str(_logKeyRecipientType, _recipientTypeUser).Msg("share creation failed") return libregraph.Permission{}, err } shareid = createShareResponse.GetShare().GetId().GetOpaqueId() @@ -295,7 +411,8 @@ func (s DriveItemPermissionsService) Invite(ctx context.Context, resourceId *sto if user, ok := revactx.ContextGetUser(ctx); ok { userIdentity, err := userIdToIdentity(ctx, s.identityCache, tenantId, user.GetId().GetOpaqueId()) if err != nil { - s.logger.Error().Err(err).Msg("identity lookup failed") + logger.Error().Err(err).Str(_logKeyErrorCode, errorCodeForError(err)).Str(_logKeyItemID, storagespace.FormatResourceID(resourceId)).Msg("identity lookup failed") + setSpanErrorStatus(span, err) return libregraph.Permission{}, errorcode.New(errorcode.InvalidRequest, err.Error()) } permission.SetInvitation(libregraph.SharingInvitation{ @@ -385,19 +502,28 @@ func createShareRequestToMail(mail string, info *storageprovider.ResourceInfo, c } // SpaceRootInvite handles invitation request on project spaces -func (s DriveItemPermissionsService) SpaceRootInvite(ctx context.Context, driveID *storageprovider.ResourceId, invite libregraph.DriveItemInvite) (libregraph.Permission, error) { +func (s DriveItemPermissionsService) SpaceRootInvite(ctx context.Context, driveID *storageprovider.ResourceId, invite libregraph.DriveItemInvite) (_ libregraph.Permission, err error) { + ctx, span := s.tp.Tracer(_tracerName).Start(ctx, "SpaceRootInvite") + defer func() { endSpan(span, err) }() + logger := s.logger.SubloggerWithRequestID(ctx) + gatewayClient, err := s.gatewaySelector.Next() if err != nil { + errorEvent(&logger, err).Str(_logKeyDriveID, storagespace.FormatResourceID(driveID)).Msg("could not select next gateway client") return libregraph.Permission{}, err } space, err := utils.GetSpace(ctx, storagespace.FormatResourceID(driveID), gatewayClient) if err != nil { - return libregraph.Permission{}, errorcode.FromUtilsStatusCodeError(err) + spaceErr := errorcode.FromUtilsStatusCodeError(err) + errorEvent(&logger, spaceErr).Str(_logKeyDriveID, storagespace.FormatResourceID(driveID)).Msg("could not get space") + return libregraph.Permission{}, spaceErr } if space.SpaceType != _spaceTypeProject { - return libregraph.Permission{}, errorcode.New(errorcode.InvalidRequest, "unsupported space type") + spaceTypeErr := errorcode.New(errorcode.InvalidRequest, "unsupported space type") + logger.Debug().Err(spaceTypeErr).Str(_logKeyDriveID, storagespace.FormatResourceID(driveID)).Str(_logKeySpaceType, space.GetSpaceType()).Msg("unsupported space type") + return libregraph.Permission{}, spaceTypeErr } rootResourceID := space.GetRoot() @@ -405,21 +531,27 @@ func (s DriveItemPermissionsService) SpaceRootInvite(ctx context.Context, driveI } // ListPermissions lists the permissions of a driveItem -func (s DriveItemPermissionsService) ListPermissions(ctx context.Context, itemID *storageprovider.ResourceId, queryOptions ListPermissionsQueryOptions) (libregraph.CollectionOfPermissionsWithAllowedValues, error) { +func (s DriveItemPermissionsService) ListPermissions(ctx context.Context, itemID *storageprovider.ResourceId, queryOptions ListPermissionsQueryOptions) (_ libregraph.CollectionOfPermissionsWithAllowedValues, err error) { + ctx, span := s.tp.Tracer(_tracerName).Start(ctx, "ListPermissions") + defer func() { endSpan(span, err) }() + logger := s.logger.SubloggerWithRequestID(ctx) + collectionOfPermissions := libregraph.CollectionOfPermissionsWithAllowedValues{} gatewayClient, err := s.gatewaySelector.Next() if err != nil { + errorEvent(&logger, err).Str(_logKeyItemID, storagespace.FormatResourceID(itemID)).Msg("could not select next gateway client") return collectionOfPermissions, err } statResponse, err := gatewayClient.Stat(ctx, &storageprovider.StatRequest{Ref: &storageprovider.Reference{ResourceId: itemID}}) if err := errorcode.FromStat(statResponse, err); err != nil { - s.logger.Warn().Err(err).Interface("stat.res", statResponse).Msg("stat failed") + errorEvent(&logger, err).Str(_logKeyItemID, storagespace.FormatResourceID(itemID)).Msg("stat failed") return collectionOfPermissions, err } var condition string if condition, err = roleConditionForResourceType(statResponse.GetInfo()); err != nil { + logger.Debug().Err(err).Str(_logKeyItemID, storagespace.FormatResourceID(itemID)).Msg("unsupported resource type") return collectionOfPermissions, err } @@ -470,6 +602,7 @@ func (s DriveItemPermissionsService) ListPermissions(ctx context.Context, itemID share.ResourceIDFilter(itemID), }, driveItems) if err != nil { + errorEvent(&logger, err).Str(_logKeyItemID, storagespace.FormatResourceID(itemID)).Msg("could not list space root shares") return collectionOfPermissions, err } } else { @@ -478,6 +611,7 @@ func (s DriveItemPermissionsService) ListPermissions(ctx context.Context, itemID share.ResourceIDFilter(itemID), }, driveItems) if err != nil { + errorEvent(&logger, err).Str(_logKeyItemID, storagespace.FormatResourceID(itemID)).Msg("could not list user shares") return collectionOfPermissions, err } if s.config.IncludeOCMSharees { @@ -488,6 +622,7 @@ func (s DriveItemPermissionsService) ListPermissions(ctx context.Context, itemID }, }, driveItems) if err != nil { + errorEvent(&logger, err).Str(_logKeyItemID, storagespace.FormatResourceID(itemID)).Msg("could not list ocm shares") return collectionOfPermissions, err } } @@ -499,6 +634,7 @@ func (s DriveItemPermissionsService) ListPermissions(ctx context.Context, itemID publicshare.ResourceIDFilter(itemID), }, driveItems) if err != nil { + errorEvent(&logger, err).Str(_logKeyItemID, storagespace.FormatResourceID(itemID)).Msg("could not list public shares") return collectionOfPermissions, err } } @@ -518,21 +654,30 @@ func (s DriveItemPermissionsService) ListPermissions(ctx context.Context, itemID } // ListSpaceRootPermissions handles ListPermissions request on project spaces -func (s DriveItemPermissionsService) ListSpaceRootPermissions(ctx context.Context, driveID *storageprovider.ResourceId, queryOptions ListPermissionsQueryOptions) (libregraph.CollectionOfPermissionsWithAllowedValues, error) { +func (s DriveItemPermissionsService) ListSpaceRootPermissions(ctx context.Context, driveID *storageprovider.ResourceId, queryOptions ListPermissionsQueryOptions) (_ libregraph.CollectionOfPermissionsWithAllowedValues, err error) { + ctx, span := s.tp.Tracer(_tracerName).Start(ctx, "ListSpaceRootPermissions") + defer func() { endSpan(span, err) }() + logger := s.logger.SubloggerWithRequestID(ctx) + collectionOfPermissions := libregraph.CollectionOfPermissionsWithAllowedValues{} gatewayClient, err := s.gatewaySelector.Next() if err != nil { + errorEvent(&logger, err).Str(_logKeyDriveID, storagespace.FormatResourceID(driveID)).Msg("could not select next gateway client") return collectionOfPermissions, err } space, err := utils.GetSpace(ctx, storagespace.FormatResourceID(driveID), gatewayClient) if err != nil { - return collectionOfPermissions, errorcode.FromUtilsStatusCodeError(err) + spaceErr := errorcode.FromUtilsStatusCodeError(err) + errorEvent(&logger, spaceErr).Str(_logKeyDriveID, storagespace.FormatResourceID(driveID)).Msg("could not get space") + return collectionOfPermissions, spaceErr } isSupportedSpaceType := slices.Contains([]string{_spaceTypeProject, _spaceTypePersonal, _spaceTypeVirtual}, space.GetSpaceType()) if !isSupportedSpaceType { - return collectionOfPermissions, errorcode.New(errorcode.InvalidRequest, "unsupported space type") + spaceTypeErr := errorcode.New(errorcode.InvalidRequest, "unsupported space type") + logger.Debug().Err(spaceTypeErr).Str(_logKeyDriveID, storagespace.FormatResourceID(driveID)).Str(_logKeySpaceType, space.GetSpaceType()).Msg("unsupported space type") + return collectionOfPermissions, spaceTypeErr } rootResourceID := space.GetRoot() @@ -540,7 +685,11 @@ func (s DriveItemPermissionsService) ListSpaceRootPermissions(ctx context.Contex } // DeletePermission deletes a permission from a drive item -func (s DriveItemPermissionsService) DeletePermission(ctx context.Context, itemID *storageprovider.ResourceId, permissionID string) error { +func (s DriveItemPermissionsService) DeletePermission(ctx context.Context, itemID *storageprovider.ResourceId, permissionID string) (err error) { + ctx, span := s.tp.Tracer(_tracerName).Start(ctx, "DeletePermission") + defer func() { endSpan(span, err) }() + logger := s.logger.SubloggerWithRequestID(ctx) + var permissionType permissionType sharedResourceID, err := s.getLinkPermissionResourceID(ctx, permissionID) @@ -563,7 +712,10 @@ func (s DriveItemPermissionsService) DeletePermission(ctx context.Context, itemI } } + // the ocm lookup replaces the error of the share lookups, keep it for logging + var lookupErr error if sharedResourceID == nil && s.config.IncludeOCMSharees { + lookupErr = err sharedResourceID, err = s.getOCMPermissionResourceID(ctx, permissionID) if err == nil { permissionType = OCM @@ -572,47 +724,74 @@ func (s DriveItemPermissionsService) DeletePermission(ctx context.Context, itemI switch { case err != nil: + fallbackErrorEvent(&logger, err, lookupErr, _logKeyLookupError).Str(_logKeyItemID, storagespace.FormatResourceID(itemID)).Str(_logKeyPermissionID, permissionID).Msg("could not resolve permission") + setSpanErrorStatus(span, lookupErr) return err case permissionType == Unknown: + logger.Debug().Str(_logKeyItemID, storagespace.FormatResourceID(itemID)).Str(_logKeyPermissionID, permissionID).Msg("permission not found") return errorcode.New(errorcode.ItemNotFound, "permission not found") case sharedResourceID == nil: + logger.Debug().Str(_logKeyItemID, storagespace.FormatResourceID(itemID)).Str(_logKeyPermissionID, permissionID).Msg("could not resolve the shared resource of the permission") return errorcode.New(errorcode.ItemNotFound, "failed to resolve resource id for shared resource") } // The resourceID of the shared resource need to match the item ID from the Request Path // otherwise this is an invalid Request. if !utils.ResourceIDEqual(sharedResourceID, itemID) { - s.logger.Debug().Msg("resourceID of shared does not match itemID") + logger.Debug().Str(_logKeyItemID, storagespace.FormatResourceID(itemID)).Str(_logKeyPermissionID, permissionID).Msg("resourceID of shared does not match itemID") return errorcode.New(errorcode.InvalidRequest, "permissionID and itemID do not match") } switch permissionType { case User, Space: - return s.removeUserShare(ctx, permissionID) + if err := s.removeUserShare(ctx, permissionID); err != nil { + errorEvent(&logger, err).Str(_logKeyItemID, storagespace.FormatResourceID(itemID)).Str(_logKeyPermissionID, permissionID).Msg("could not remove permission") + return err + } + return nil case Public: - return s.removePublicShare(ctx, permissionID) + if err := s.removePublicShare(ctx, permissionID); err != nil { + errorEvent(&logger, err).Str(_logKeyItemID, storagespace.FormatResourceID(itemID)).Str(_logKeyPermissionID, permissionID).Msg("could not remove permission") + return err + } + return nil case OCM: - return s.removeOCMPermission(ctx, permissionID) + if err := s.removeOCMPermission(ctx, permissionID); err != nil { + errorEvent(&logger, err).Str(_logKeyItemID, storagespace.FormatResourceID(itemID)).Str(_logKeyPermissionID, permissionID).Msg("could not remove permission") + return err + } + return nil default: // This should never be reached - return errorcode.New(errorcode.GeneralException, "failed to delete permission") + unknownTypeErr := errorcode.New(errorcode.GeneralException, "failed to delete permission") + errorEvent(&logger, unknownTypeErr).Str(_logKeyItemID, storagespace.FormatResourceID(itemID)).Str(_logKeyPermissionID, permissionID).Int(_logKeyPermissionType, int(permissionType)).Msg("unknown permission type") + return unknownTypeErr } } // DeleteSpaceRootPermission deletes a permission on the root item of a project space -func (s DriveItemPermissionsService) DeleteSpaceRootPermission(ctx context.Context, driveID *storageprovider.ResourceId, permissionID string) error { +func (s DriveItemPermissionsService) DeleteSpaceRootPermission(ctx context.Context, driveID *storageprovider.ResourceId, permissionID string) (err error) { + ctx, span := s.tp.Tracer(_tracerName).Start(ctx, "DeleteSpaceRootPermission") + defer func() { endSpan(span, err) }() + logger := s.logger.SubloggerWithRequestID(ctx) + gatewayClient, err := s.gatewaySelector.Next() if err != nil { + errorEvent(&logger, err).Str(_logKeyDriveID, storagespace.FormatResourceID(driveID)).Str(_logKeyPermissionID, permissionID).Msg("could not select next gateway client") return err } space, err := utils.GetSpace(ctx, storagespace.FormatResourceID(driveID), gatewayClient) if err != nil { - return errorcode.FromUtilsStatusCodeError(err) + spaceErr := errorcode.FromUtilsStatusCodeError(err) + errorEvent(&logger, spaceErr).Str(_logKeyDriveID, storagespace.FormatResourceID(driveID)).Str(_logKeyPermissionID, permissionID).Msg("could not get space") + return spaceErr } if space.SpaceType != _spaceTypeProject { - return errorcode.New(errorcode.InvalidRequest, "unsupported space type") + spaceTypeErr := errorcode.New(errorcode.InvalidRequest, "unsupported space type") + logger.Debug().Err(spaceTypeErr).Str(_logKeyDriveID, storagespace.FormatResourceID(driveID)).Str(_logKeyPermissionID, permissionID).Str(_logKeySpaceType, space.GetSpaceType()).Msg("unsupported space type") + return spaceTypeErr } rootResourceID := space.GetRoot() @@ -620,23 +799,32 @@ func (s DriveItemPermissionsService) DeleteSpaceRootPermission(ctx context.Conte } // UpdatePermission updates a permission on a drive item -func (s DriveItemPermissionsService) UpdatePermission(ctx context.Context, itemID *storageprovider.ResourceId, permissionID string, newPermission libregraph.Permission) (libregraph.Permission, error) { +func (s DriveItemPermissionsService) UpdatePermission(ctx context.Context, itemID *storageprovider.ResourceId, permissionID string, newPermission libregraph.Permission) (_ libregraph.Permission, err error) { + ctx, span := s.tp.Tracer(_tracerName).Start(ctx, "UpdatePermission") + defer func() { endSpan(span, err) }() + logger := s.logger.SubloggerWithRequestID(ctx) + oldPermission, sharedResourceID, err := s.getPermissionByID(ctx, permissionID, itemID) - // try to get the permission from ocm if the permission was not found first place + // try to get the permission from ocm if the permission was not found first place, + // the ocm lookup replaces the error of the share lookup, keep it for logging + var lookupErr error if err != nil && s.config.IncludeOCMSharees { + lookupErr = err oldPermission, sharedResourceID, err = s.getOCMPermissionByID(ctx, permissionID, itemID) } // if we still can't find the permission, return an error if err != nil { + fallbackErrorEvent(&logger, err, lookupErr, _logKeyLookupError).Str(_logKeyItemID, storagespace.FormatResourceID(itemID)).Str(_logKeyPermissionID, permissionID).Msg("could not resolve permission") + setSpanErrorStatus(span, lookupErr) return libregraph.Permission{}, err } // The resourceID of the shared resource need to match the item ID from the Request Path // otherwise this is an invalid Request. if !utils.ResourceIDEqual(sharedResourceID, itemID) { - s.logger.Debug().Msg("resourceID of shared does not match itemID") + logger.Debug().Str(_logKeyItemID, storagespace.FormatResourceID(itemID)).Str(_logKeyPermissionID, permissionID).Msg("resourceID of shared does not match itemID") return libregraph.Permission{}, errorcode.New(errorcode.InvalidRequest, "permissionID and itemID do not match") } @@ -644,6 +832,7 @@ func (s DriveItemPermissionsService) UpdatePermission(ctx context.Context, itemI if _, ok := oldPermission.GetLinkOk(); ok { updatedPermission, err := s.updatePublicLinkPermission(ctx, permissionID, itemID, &newPermission) if err != nil { + errorEvent(&logger, err).Str(_logKeyItemID, storagespace.FormatResourceID(itemID)).Str(_logKeyPermissionID, permissionID).Msg("could not update permission") return libregraph.Permission{}, err } return *updatedPermission, nil @@ -656,19 +845,72 @@ func (s DriveItemPermissionsService) UpdatePermission(ctx context.Context, itemI } // This is an ocm share + var ocmErr error if s.config.IncludeOCMSharees { - updatePermission, err := s.updateOCMPermission(ctx, permissionID, itemID, &newPermission) - if err == nil { + var updatePermission *libregraph.Permission + updatePermission, ocmErr = s.updateOCMPermission(ctx, permissionID, itemID, &newPermission) + if ocmErr == nil { return *updatePermission, nil } } + if err != nil { + // the user share error is returned, but the ocm update may have failed for the more severe cause + fallbackErrorEvent(&logger, err, ocmErr, _logKeyOCMError).Str(_logKeyItemID, storagespace.FormatResourceID(itemID)).Str(_logKeyPermissionID, permissionID).Msg("could not update permission") + setSpanErrorStatus(span, ocmErr) + } return libregraph.Permission{}, err } // UpdateSpaceRootPermission updates a permission on the root item of a project space -func (s DriveItemPermissionsService) UpdateSpaceRootPermission(ctx context.Context, driveID *storageprovider.ResourceId, permissionID string, newPermission libregraph.Permission) (libregraph.Permission, error) { +func (s DriveItemPermissionsService) UpdateSpaceRootPermission(ctx context.Context, driveID *storageprovider.ResourceId, permissionID string, newPermission libregraph.Permission) (_ libregraph.Permission, err error) { + ctx, span := s.tp.Tracer(_tracerName).Start(ctx, "UpdateSpaceRootPermission") + defer func() { endSpan(span, err) }() + logger := s.logger.SubloggerWithRequestID(ctx) + + gatewayClient, err := s.gatewaySelector.Next() + if err != nil { + errorEvent(&logger, err).Str(_logKeyDriveID, storagespace.FormatResourceID(driveID)).Str(_logKeyPermissionID, permissionID).Msg("could not select next gateway client") + return libregraph.Permission{}, err + } + + space, err := utils.GetSpace(ctx, storagespace.FormatResourceID(driveID), gatewayClient) + if err != nil { + spaceErr := errorcode.FromUtilsStatusCodeError(err) + errorEvent(&logger, spaceErr).Str(_logKeyDriveID, storagespace.FormatResourceID(driveID)).Str(_logKeyPermissionID, permissionID).Msg("could not get space") + return libregraph.Permission{}, spaceErr + } + + if space.SpaceType != _spaceTypeProject { + spaceTypeErr := errorcode.New(errorcode.InvalidRequest, "unsupported space type") + logger.Debug().Err(spaceTypeErr).Str(_logKeyDriveID, storagespace.FormatResourceID(driveID)).Str(_logKeyPermissionID, permissionID).Str(_logKeySpaceType, space.GetSpaceType()).Msg("unsupported space type") + return libregraph.Permission{}, spaceTypeErr + } + + rootResourceID := space.GetRoot() + return s.UpdatePermission(ctx, rootResourceID, permissionID, newPermission) +} + +// GetPermission returns a single permission of a drive item. +// It reuses ListPermissions, so only permissions visible in the listing of the item can be retrieved. +func (s DriveItemPermissionsService) GetPermission(ctx context.Context, itemID *storageprovider.ResourceId, permissionID string) (libregraph.Permission, error) { + collection, err := s.ListPermissions(ctx, itemID, ListPermissionsQueryOptions{}) + if err != nil { + return libregraph.Permission{}, err + } + + for _, permission := range collection.Value { + if permission.GetId() == permissionID { + return permission, nil + } + } + + return libregraph.Permission{}, errorcode.New(errorcode.ItemNotFound, "permission not found") +} + +// GetSpaceRootPermission returns a single permission on the root item of a project space +func (s DriveItemPermissionsService) GetSpaceRootPermission(ctx context.Context, driveID *storageprovider.ResourceId, permissionID string) (libregraph.Permission, error) { gatewayClient, err := s.gatewaySelector.Next() if err != nil { return libregraph.Permission{}, err @@ -679,12 +921,11 @@ func (s DriveItemPermissionsService) UpdateSpaceRootPermission(ctx context.Conte return libregraph.Permission{}, errorcode.FromUtilsStatusCodeError(err) } - if space.SpaceType != _spaceTypeProject { + if space.GetSpaceType() != _spaceTypeProject { return libregraph.Permission{}, errorcode.New(errorcode.InvalidRequest, "unsupported space type") } - rootResourceID := space.GetRoot() - return s.UpdatePermission(ctx, rootResourceID, permissionID, newPermission) + return s.GetPermission(ctx, space.GetRoot(), permissionID) } // DriveItemPermissionsApi is the api that registers the http endpoints which expose needed operation to the graph api. @@ -1023,3 +1264,53 @@ func (api DriveItemPermissionsApi) UpdateSpaceRootPermission(w http.ResponseWrit render.Status(r, http.StatusOK) render.JSON(w, r, &updatedPermission) } + +// GetPermission handles GetPermission requests +func (api DriveItemPermissionsApi) GetPermission(w http.ResponseWriter, r *http.Request) { + _, itemID, err := GetDriveAndItemIDParam(r, &api.logger) + if err != nil { + api.logger.Debug().Err(err).Msg(invalidIdMsg) + errorcode.RenderError(w, r, err) + return + } + + permissionID, err := url.PathUnescape(chi.URLParam(r, "permissionID")) + if err != nil || permissionID == "" { + api.logger.Debug().Err(err).Msg("could not parse permissionID") + errorcode.InvalidRequest.Render(w, r, http.StatusBadRequest, "invalid permissionID") + return + } + + permission, err := api.driveItemPermissionsService.GetPermission(r.Context(), itemID, permissionID) + if err != nil { + errorcode.RenderError(w, r, err) + return + } + render.Status(r, http.StatusOK) + render.JSON(w, r, &permission) +} + +// GetSpaceRootPermission handles GetPermission requests on a space root +func (api DriveItemPermissionsApi) GetSpaceRootPermission(w http.ResponseWriter, r *http.Request) { + driveID, err := parseIDParam(r, "driveID") + if err != nil { + api.logger.Debug().Err(err).Msg(parseDriveIDErrMsg) + errorcode.InvalidRequest.Render(w, r, http.StatusUnprocessableEntity, parseDriveIDErrMsg) + return + } + + permissionID, err := url.PathUnescape(chi.URLParam(r, "permissionID")) + if err != nil || permissionID == "" { + api.logger.Debug().Err(err).Msg("could not parse permissionID") + errorcode.InvalidRequest.Render(w, r, http.StatusBadRequest, "invalid permissionID") + return + } + + permission, err := api.driveItemPermissionsService.GetSpaceRootPermission(r.Context(), &driveID, permissionID) + if err != nil { + errorcode.RenderError(w, r, err) + return + } + render.Status(r, http.StatusOK) + render.JSON(w, r, &permission) +} diff --git a/services/graph/pkg/service/v0/api_driveitem_permissions_links.go b/services/graph/pkg/service/v0/api_driveitem_permissions_links.go index 817cbc9515..aaf664239a 100644 --- a/services/graph/pkg/service/v0/api_driveitem_permissions_links.go +++ b/services/graph/pkg/service/v0/api_driveitem_permissions_links.go @@ -13,11 +13,11 @@ import ( types "github.com/cs3org/go-cs3apis/cs3/types/v1beta1" "github.com/go-chi/chi/v5" "github.com/go-chi/render" + libregraph "github.com/opencloud-eu/libre-graph-api-go" "github.com/opencloud-eu/opencloud/services/graph/pkg/errorcode" "github.com/opencloud-eu/opencloud/services/graph/pkg/linktype" "github.com/opencloud-eu/reva/v2/pkg/storagespace" "github.com/opencloud-eu/reva/v2/pkg/utils" - libregraph "github.com/opencloud-eu/libre-graph-api-go" ) func (s DriveItemPermissionsService) CreateLink(ctx context.Context, driveItemID *storageprovider.ResourceId, createLink libregraph.DriveItemCreateLink) (libregraph.Permission, error) { @@ -230,6 +230,8 @@ func (api DriveItemPermissionsApi) SetLinkPassword(w http.ResponseWriter, r *htt newPermission, err := api.driveItemPermissionsService.SetPublicLinkPassword(ctx, itemID, permissionID, password.GetPassword()) if err != nil { + logger := api.logger.SubloggerWithRequestID(ctx) + errorEvent(&logger, err).Str(_logKeyItemID, storagespace.FormatResourceID(itemID)).Str(_logKeyPermissionID, permissionID).Msg("could not set link password") errorcode.RenderError(w, r, err) return } @@ -264,6 +266,8 @@ func (api DriveItemPermissionsApi) SetSpaceRootLinkPassword(w http.ResponseWrite ctx := r.Context() newPermission, err := api.driveItemPermissionsService.SetPublicLinkPasswordOnSpaceRoot(ctx, &driveID, permissionID, password.GetPassword()) if err != nil { + logger := api.logger.SubloggerWithRequestID(ctx) + errorEvent(&logger, err).Str(_logKeyDriveID, storagespace.FormatResourceID(&driveID)).Str(_logKeyPermissionID, permissionID).Msg("could not set link password") errorcode.RenderError(w, r, err) return } @@ -275,7 +279,8 @@ func (api DriveItemPermissionsApi) SetSpaceRootLinkPassword(w http.ResponseWrite func (s DriveItemPermissionsService) updatePublicLinkPermission(ctx context.Context, permissionID string, itemID *storageprovider.ResourceId, newPermission *libregraph.Permission) (perm *libregraph.Permission, err error) { gatewayClient, err := s.gatewaySelector.Next() if err != nil { - s.logger.Error().Err(err).Msg("could not select next gateway client") + logger := s.logger.SubloggerWithRequestID(ctx) + logger.Error().Err(err).Str(_logKeyPermissionID, permissionID).Msg("could not select next gateway client") return nil, errorcode.New(errorcode.GeneralException, err.Error()) } diff --git a/services/graph/pkg/service/v0/api_driveitem_permissions_links_test.go b/services/graph/pkg/service/v0/api_driveitem_permissions_links_test.go index 47124eef0e..39616fdb23 100644 --- a/services/graph/pkg/service/v0/api_driveitem_permissions_links_test.go +++ b/services/graph/pkg/service/v0/api_driveitem_permissions_links_test.go @@ -54,7 +54,7 @@ var _ = Describe("createLinkTests", func() { cache := cache.NewIdentityCache(cache.IdentityCacheWithGatewaySelector(gatewaySelector)) cfg := defaults.FullDefaultConfig() - svc, err = service.NewDriveItemPermissionsService(logger, gatewaySelector, cache, cfg) + svc, err = service.NewDriveItemPermissionsService(logger, gatewaySelector, cache, cfg, nil) Expect(err).ToNot(HaveOccurred()) driveItemId = &provider.ResourceId{ StorageId: "1", diff --git a/services/graph/pkg/service/v0/api_driveitem_permissions_test.go b/services/graph/pkg/service/v0/api_driveitem_permissions_test.go index cf6ecd44c7..c5bce19f34 100644 --- a/services/graph/pkg/service/v0/api_driveitem_permissions_test.go +++ b/services/graph/pkg/service/v0/api_driveitem_permissions_test.go @@ -8,26 +8,42 @@ import ( "net/http" "net/http/httptest" "slices" + "strings" "time" gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1" grouppb "github.com/cs3org/go-cs3apis/cs3/identity/group/v1beta1" userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" + invitepb "github.com/cs3org/go-cs3apis/cs3/ocm/invite/v1beta1" + ocmprovider "github.com/cs3org/go-cs3apis/cs3/ocm/provider/v1beta1" + cs3rpc "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" + ocm "github.com/cs3org/go-cs3apis/cs3/sharing/ocm/v1beta1" provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" types "github.com/cs3org/go-cs3apis/cs3/types/v1beta1" "github.com/go-chi/chi/v5" + "github.com/go-chi/chi/v5/middleware" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" + gomegatypes "github.com/onsi/gomega/types" libregraph "github.com/opencloud-eu/libre-graph-api-go" "github.com/opencloud-eu/opencloud/services/graph/pkg/config" + "github.com/prometheus/client_golang/prometheus" + "github.com/rs/zerolog" "github.com/stretchr/testify/mock" "github.com/tidwall/gjson" + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/codes" + sdktrace "go.opentelemetry.io/otel/sdk/trace" + "go.opentelemetry.io/otel/sdk/trace/tracetest" + "go.opentelemetry.io/otel/trace" + "google.golang.org/grpc" roleconversions "github.com/opencloud-eu/reva/v2/pkg/conversions" revactx "github.com/opencloud-eu/reva/v2/pkg/ctx" "github.com/opencloud-eu/reva/v2/pkg/rgrpc/status" + "github.com/opencloud-eu/reva/v2/pkg/rgrpc/todo/pool" "github.com/opencloud-eu/reva/v2/pkg/storagespace" "github.com/opencloud-eu/reva/v2/pkg/utils" cs3mocks "github.com/opencloud-eu/reva/v2/tests/cs3mocks/mocks" @@ -39,10 +55,80 @@ import ( "github.com/opencloud-eu/opencloud/services/graph/pkg/errorcode" identitycache "github.com/opencloud-eu/opencloud/services/graph/pkg/identity/cache" "github.com/opencloud-eu/opencloud/services/graph/pkg/linktype" + "github.com/opencloud-eu/opencloud/services/graph/pkg/metrics" svc "github.com/opencloud-eu/opencloud/services/graph/pkg/service/v0" "github.com/opencloud-eu/opencloud/services/graph/pkg/unifiedrole" ) +// logEntries decodes the JSON lines written by a zerolog logger. +func logEntries(buf *bytes.Buffer) []map[string]any { + var entries []map[string]any + dec := json.NewDecoder(buf) + for dec.More() { + entry := map[string]any{} + Expect(dec.Decode(&entry)).To(Succeed()) + entries = append(entries, entry) + } + return entries +} + +// rawLog re-encodes the log entries, so a sentinel can be searched for in every field. +func rawLog(entries []map[string]any) string { + raw, err := json.Marshal(entries) + Expect(err).ToNot(HaveOccurred()) + return string(raw) +} + +// newSpanRecorder returns a span recorder and a TracerProvider recording into it. +func newSpanRecorder() (*tracetest.SpanRecorder, *sdktrace.TracerProvider) { + sr := tracetest.NewSpanRecorder() + tp := sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(sr)) + DeferCleanup(func() { + Expect(tp.Shutdown(context.Background())).To(Succeed()) + }) + return sr, tp +} + +// endedSpan returns the single ended span with the given name. It checks that the span carries no +// events and none of the sentinels in its status or attributes. +func endedSpan(sr *tracetest.SpanRecorder, name string, sentinels ...string) sdktrace.ReadOnlySpan { + var spans []sdktrace.ReadOnlySpan + for _, s := range sr.Ended() { + if s.Name() == name { + spans = append(spans, s) + } + } + Expect(spans).To(HaveLen(1)) + span := spans[0] + Expect(span.Events()).To(BeEmpty()) + raw, err := json.Marshal([]any{span.Status(), span.Attributes()}) + Expect(err).ToNot(HaveOccurred()) + for _, sentinel := range sentinels { + Expect(string(raw)).ToNot(ContainSubstring(sentinel)) + } + return span +} + +// gatewayHelperEntry matches the error entry a share helper logs when it cannot select a gateway. +func gatewayHelperEntry(message, errorText string) gomegatypes.GomegaMatcher { + return SatisfyAll( + HaveKeyWithValue("level", "error"), + HaveKeyWithValue("message", message), + HaveKeyWithValue("error", errorText), + ) +} + +// entriesAtLevel returns the log entries logged at the given level. +func entriesAtLevel(entries []map[string]any, level string) []map[string]any { + var filtered []map[string]any + for _, entry := range entries { + if entry["level"] == level { + filtered = append(filtered, entry) + } + } + return filtered +} + var _ = Describe("DriveItemPermissionsService", func() { var ( driveItemPermissionsService svc.DriveItemPermissionsService @@ -73,7 +159,7 @@ var _ = Describe("DriveItemPermissionsService", func() { cache = identitycache.NewIdentityCache(identitycache.IdentityCacheWithGatewaySelector(gatewaySelector)) cfg = defaults.FullDefaultConfig() - service, err := svc.NewDriveItemPermissionsService(logger, gatewaySelector, cache, cfg) + service, err := svc.NewDriveItemPermissionsService(logger, gatewaySelector, cache, cfg, nil) Expect(err).ToNot(HaveOccurred()) driveItemPermissionsService = service ctx = revactx.ContextSetUser(context.Background(), currentUser) @@ -99,6 +185,326 @@ var _ = Describe("DriveItemPermissionsService", func() { }) + // newLoggedService returns a service logging into a new buffer. It uses the mocks and the + // config of the current spec, so call it after the spec has adjusted them. + newLoggedService := func() (svc.DriveItemPermissionsService, *bytes.Buffer) { + logBuf := &bytes.Buffer{} + service, err := svc.NewDriveItemPermissionsService(log.Logger{Logger: zerolog.New(logBuf)}, gatewaySelector, cache, cfg, nil) + Expect(err).ToNot(HaveOccurred()) + return service, logBuf + } + + // A failing gateway selection is an unexpected failure of every operation, logged with its error text. + // Where a probing helper selects the gateway, the helper also logs the selector's error. + DescribeTable("reports a gateway selection failure once, as error log correlated with the request and as error span", + func(name string, call func(context.Context, svc.DriveItemPermissionsService) error, ids map[string]string, errorText gomegatypes.GomegaMatcher, helperEntries int) { + gatewayErr := errors.New("no gateway available at 10.0.0.42") + gatewaySelector.EXPECT().Next().Unset() + gatewaySelector.EXPECT().Next().Return(nil, gatewayErr) + var logBuf bytes.Buffer + sr, tp := newSpanRecorder() + service, err := svc.NewDriveItemPermissionsService(log.Logger{Logger: zerolog.New(&logBuf)}, gatewaySelector, cache, cfg, tp) + Expect(err).ToNot(HaveOccurred()) + + Expect(call(context.WithValue(ctx, middleware.RequestIDKey, "request-42"), service)).To(MatchError(gatewayErr)) + + // the error text is added once per entry: decoding into a map would hide a duplicate key + for line := range strings.SplitSeq(strings.TrimSpace(logBuf.String()), "\n") { + Expect(strings.Count(line, `"error":`)).To(BeNumerically("<=", 1), line) + } + entries := logEntries(&logBuf) + // the operation and the helpers log one entry each, all correlated with the request + const helperMessage = "selecting gatewaySelector failed" + var correlated, helpers []map[string]any + for _, entry := range entriesAtLevel(entries, "error") { + if entry["message"] == helperMessage { + helpers = append(helpers, entry) + } else { + correlated = append(correlated, entry) + } + } + Expect(correlated).To(HaveLen(1)) + Expect(helpers).To(HaveLen(helperEntries)) + for _, entry := range helpers { + Expect(entry).To(SatisfyAll( + gatewayHelperEntry(helperMessage, gatewayErr.Error()), + HaveKeyWithValue("request-id", "request-42"), + HaveKeyWithValue("permissionID", "permissionid"), + )) + } + expected := []gomegatypes.GomegaMatcher{ + HaveKeyWithValue("request-id", "request-42"), + HaveKeyWithValue("errorCode", "generalException"), + errorText, + } + for k, v := range ids { + expected = append(expected, HaveKeyWithValue(k, v)) + } + Expect(correlated[0]).To(SatisfyAll(expected...)) + // no serialized requests, responses or gateway clients + for _, payloadKey := range []string{"stat.res", "gateway.res", "Body", "body", "request", "response"} { + Expect(entries).ToNot(ContainElement(HaveKey(payloadKey))) + } + + // the span carries the error code only, the error message is not recorded + Expect(sr.Ended()).To(HaveLen(1)) + span := endedSpan(sr, name, "10.0.0.42") + Expect(span.Status().Code).To(Equal(codes.Error)) + Expect(span.Status().Description).To(Equal("generalException")) + Expect(span.Attributes()).To(ContainElement(attribute.String("error.type", "generalException"))) + }, + Entry("Invite", "Invite", func(ctx context.Context, s svc.DriveItemPermissionsService) error { + _, err := s.Invite(ctx, driveItemId, libregraph.DriveItemInvite{}) + return err + }, map[string]string{"itemID": "1$2!3"}, HaveKeyWithValue("error", "no gateway available at 10.0.0.42"), 0), + Entry("SpaceRootInvite", "SpaceRootInvite", func(ctx context.Context, s svc.DriveItemPermissionsService) error { + _, err := s.SpaceRootInvite(ctx, &provider.ResourceId{StorageId: "1", SpaceId: "2"}, libregraph.DriveItemInvite{}) + return err + }, map[string]string{"driveID": "1$2"}, HaveKeyWithValue("error", "no gateway available at 10.0.0.42"), 0), + Entry("ListPermissions", "ListPermissions", func(ctx context.Context, s svc.DriveItemPermissionsService) error { + _, err := s.ListPermissions(ctx, driveItemId, svc.ListPermissionsQueryOptions{}) + return err + }, map[string]string{"itemID": "1$2!3"}, HaveKeyWithValue("error", "no gateway available at 10.0.0.42"), 0), + Entry("ListSpaceRootPermissions", "ListSpaceRootPermissions", func(ctx context.Context, s svc.DriveItemPermissionsService) error { + _, err := s.ListSpaceRootPermissions(ctx, &provider.ResourceId{StorageId: "1", SpaceId: "2"}, svc.ListPermissionsQueryOptions{}) + return err + }, map[string]string{"driveID": "1$2"}, HaveKeyWithValue("error", "no gateway available at 10.0.0.42"), 0), + Entry("DeletePermission (selected by the probing helpers)", "DeletePermission", func(ctx context.Context, s svc.DriveItemPermissionsService) error { + return s.DeletePermission(ctx, driveItemId, "permissionid") + }, map[string]string{"itemID": "1$2!3", "permissionID": "permissionid"}, HaveKeyWithValue("error", "no gateway available at 10.0.0.42"), 2), + Entry("DeleteSpaceRootPermission", "DeleteSpaceRootPermission", func(ctx context.Context, s svc.DriveItemPermissionsService) error { + return s.DeleteSpaceRootPermission(ctx, &provider.ResourceId{StorageId: "1", SpaceId: "2"}, "permissionid") + }, map[string]string{"driveID": "1$2", "permissionID": "permissionid"}, HaveKeyWithValue("error", "no gateway available at 10.0.0.42"), 0), + Entry("UpdatePermission (selected by the probing helpers)", "UpdatePermission", func(ctx context.Context, s svc.DriveItemPermissionsService) error { + _, err := s.UpdatePermission(ctx, driveItemId, "permissionid", libregraph.Permission{}) + return err + }, map[string]string{"itemID": "1$2!3", "permissionID": "permissionid"}, HaveKeyWithValue("error", "no gateway available at 10.0.0.42"), 1), + Entry("UpdateSpaceRootPermission", "UpdateSpaceRootPermission", func(ctx context.Context, s svc.DriveItemPermissionsService) error { + _, err := s.UpdateSpaceRootPermission(ctx, &provider.ResourceId{StorageId: "1", SpaceId: "2"}, "permissionid", libregraph.Permission{}) + return err + }, map[string]string{"driveID": "1$2", "permissionID": "permissionid"}, HaveKeyWithValue("error", "no gateway available at 10.0.0.42"), 0), + ) + + It("does not mark the span of an expected client error as error, but records its error code", func() { + sr, tp := newSpanRecorder() + service, err := svc.NewDriveItemPermissionsService(log.NewLogger(), gatewaySelector, cache, cfg, tp) + Expect(err).ToNot(HaveOccurred()) + gatewayClient.On("ListStorageSpaces", mock.Anything, mock.Anything).Return( + &provider.ListStorageSpacesResponse{Status: status.NewNotFound(ctx, "space Project Alpha not found")}, nil) + + _, err = service.ListSpaceRootPermissions(ctx, &provider.ResourceId{StorageId: "1", SpaceId: "2"}, svc.ListPermissionsQueryOptions{}) + Expect(errorcode.IsErrorCode(err, errorcode.ItemNotFound)).To(BeTrue()) + + Expect(sr.Ended()).To(HaveLen(1)) + span := sr.Ended()[0] + Expect(span.Status().Code).To(Equal(codes.Unset)) + Expect(span.Status().Description).To(BeEmpty()) + Expect(span.Attributes()).To(ContainElement(attribute.String("error.type", "itemNotFound"))) + Expect(span.Events()).To(BeEmpty()) + }) + + // The stat failure tables use their own invite, the Invite specs share theirs between specs. + inviteAfterStat := func(s svc.DriveItemPermissionsService) error { + _, err := s.Invite(ctx, driveItemId, libregraph.DriveItemInvite{ + Roles: []string{unifiedrole.UnifiedRoleViewerID}, + Recipients: []libregraph.DriveRecipient{{ObjectId: libregraph.PtrString("1"), LibreGraphRecipientType: libregraph.PtrString("user")}}, + }) + return err + } + listAfterStat := func(s svc.DriveItemPermissionsService) error { + _, err := s.ListPermissions(ctx, driveItemId, svc.ListPermissionsQueryOptions{}) + return err + } + DescribeTable("logs stat failures by cause with the item id, without the stat payload", + func(call func(svc.DriveItemPermissionsService) error, newStatus func(context.Context, string) *cs3rpc.Status, code errorcode.ErrorCode, level string) { + service, logBuf := newLoggedService() + // decomposedfs reports a missing node as "/" + statMessage := "stat: 7c3e9a1b-parent/private-financial-report-2026.xlsx" + gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(&provider.StatResponse{ + Status: newStatus(ctx, statMessage), + Info: &provider.ResourceInfo{ + Id: driveItemId, + Path: "/private/project-plan.odt", + PermissionSet: roleconversions.NewViewerRole().CS3ResourcePermissions(), + }, + }, nil) + + Expect(call(service)).To(MatchError(errorcode.New(code, statMessage).WithOrigin(errorcode.ErrorOriginCS3))) + // nothing is shared or listed after the failed stat + gatewayClient.AssertCalled(GinkgoT(), "Stat", mock.Anything, mock.Anything) + for _, c := range gatewayClient.Calls { + Expect(c.Method).To(Equal("Stat")) + } + + entries := logEntries(logBuf) + var itemEntries []map[string]any + for _, entry := range entries { + if entry["itemID"] == storagespace.FormatResourceID(driveItemId) { + itemEntries = append(itemEntries, entry) + } + } + Expect(itemEntries).To(ConsistOf(HaveKeyWithValue("level", level))) + // the stat failure is the only entry at warn or error level + for _, entry := range entries { + if entry["level"] == "warn" || entry["level"] == "error" { + Expect(entry).To(Equal(itemEntries[0])) + } + } + // the failure is logged with its error text, whatever its level + Expect(itemEntries[0]).To(HaveKeyWithValue("error", errorcode.New(code, statMessage).WithOrigin(errorcode.ErrorOriginCS3).Error())) + for _, payloadKey := range []string{"stat.res", "res", "response", "request", "info", "Body", "body"} { + Expect(entries).ToNot(ContainElement(HaveKey(payloadKey))) + } + // the stat payload never reaches the log + raw := rawLog(entries) + for _, sentinel := range []string{"/private/project-plan.odt", "permission_set"} { + Expect(raw).ToNot(ContainSubstring(sentinel)) + } + }, + Entry("Invite: missing item as debug", inviteAfterStat, status.NewNotFound, errorcode.ItemNotFound, "debug"), + Entry("Invite: storage failure as error", inviteAfterStat, status.NewInternal, errorcode.GeneralException, "error"), + Entry("ListPermissions: missing item as debug", listAfterStat, status.NewNotFound, errorcode.ItemNotFound, "debug"), + Entry("ListPermissions: storage failure as error", listAfterStat, status.NewInternal, errorcode.GeneralException, "error"), + ) + + DescribeTable("logs unsupported space types as debug with the resource ids", + func(spaceType string, call func(svc.DriveItemPermissionsService) error, ids map[string]string) { + service, logBuf := newLoggedService() + gatewayClient.On("ListStorageSpaces", mock.Anything, mock.Anything).Return(&provider.ListStorageSpacesResponse{ + Status: status.NewOK(ctx), + StorageSpaces: []*provider.StorageSpace{{ + Id: &provider.StorageSpaceId{OpaqueId: "2"}, + SpaceType: spaceType, + Root: &provider.ResourceId{StorageId: "1", SpaceId: "2", OpaqueId: "2"}, + }}, + }, nil) + + Expect(call(service)).To(MatchError(errorcode.New(errorcode.InvalidRequest, "unsupported space type"))) + + // the request was rejected after resolving the space, before delegating to the item method + for _, c := range gatewayClient.Calls { + Expect(c.Method).To(Equal("ListStorageSpaces")) + } + + expected := []gomegatypes.GomegaMatcher{ + HaveKeyWithValue("level", "debug"), + HaveKeyWithValue("message", "unsupported space type"), + HaveKeyWithValue("spaceType", spaceType), + } + for _, k := range []string{"driveID", "permissionID", "itemID"} { + if v, ok := ids[k]; ok { + expected = append(expected, HaveKeyWithValue(k, v)) + } else { + expected = append(expected, Not(HaveKey(k))) + } + } + entries := logEntries(logBuf) + Expect(entries).To(ContainElement(SatisfyAll(expected...))) + Expect(entries).ToNot(ContainElement(HaveKeyWithValue("level", BeElementOf("error", "warn")))) + }, + Entry("SpaceRootInvite", "mountpoint", func(s svc.DriveItemPermissionsService) error { + _, err := s.SpaceRootInvite(ctx, &provider.ResourceId{StorageId: "1", SpaceId: "2"}, libregraph.DriveItemInvite{}) + return err + }, map[string]string{"driveID": "1$2"}), + Entry("ListSpaceRootPermissions", "mountpoint", func(s svc.DriveItemPermissionsService) error { + _, err := s.ListSpaceRootPermissions(ctx, &provider.ResourceId{StorageId: "1", SpaceId: "2"}, svc.ListPermissionsQueryOptions{}) + return err + }, map[string]string{"driveID": "1$2"}), + Entry("DeleteSpaceRootPermission", "personal", func(s svc.DriveItemPermissionsService) error { + return s.DeleteSpaceRootPermission(ctx, &provider.ResourceId{StorageId: "1", SpaceId: "2"}, "permissionid") + }, map[string]string{"driveID": "1$2", "permissionID": "permissionid"}), + Entry("UpdateSpaceRootPermission", "personal", func(s svc.DriveItemPermissionsService) error { + _, err := s.UpdateSpaceRootPermission(ctx, &provider.ResourceId{StorageId: "1", SpaceId: "2"}, "permissionid", libregraph.Permission{}) + return err + }, map[string]string{"driveID": "1$2", "permissionID": "permissionid"}), + ) + + var ( + spaceRootInvite = func(s svc.DriveItemPermissionsService) error { + _, err := s.SpaceRootInvite(ctx, &provider.ResourceId{StorageId: "1", SpaceId: "2"}, libregraph.DriveItemInvite{}) + return err + } + listSpaceRootPermissions = func(s svc.DriveItemPermissionsService) error { + _, err := s.ListSpaceRootPermissions(ctx, &provider.ResourceId{StorageId: "1", SpaceId: "2"}, svc.ListPermissionsQueryOptions{}) + return err + } + deleteSpaceRootPermission = func(s svc.DriveItemPermissionsService) error { + return s.DeleteSpaceRootPermission(ctx, &provider.ResourceId{StorageId: "1", SpaceId: "2"}, "permissionid") + } + updateSpaceRootPermission = func(s svc.DriveItemPermissionsService) error { + _, err := s.UpdateSpaceRootPermission(ctx, &provider.ResourceId{StorageId: "1", SpaceId: "2"}, "permissionid", libregraph.Permission{}) + return err + } + missingSpaceResponse = &provider.ListStorageSpacesResponse{Status: status.NewOK(context.Background())} + missingSpaceErr = errorcode.New(errorcode.ItemNotFound, "getting space").WithOrigin(errorcode.ErrorOriginCS3) + // storage providers may report space names or paths in their status messages + internalSpaceResponse = &provider.ListStorageSpacesResponse{Status: status.NewInternal(context.Background(), "storage provider unavailable for space Project Alpha")} + internalSpaceErr = errorcode.New(errorcode.GeneralException, "storage provider unavailable for space Project Alpha").WithOrigin(errorcode.ErrorOriginCS3) + transportSpaceErr = errorcode.New(errorcode.GeneralException, "connection refused").WithOrigin(errorcode.ErrorOriginCS3) + ) + DescribeTable("logs space lookup failures by cause with the resource ids", + func(call func(svc.DriveItemPermissionsService) error, ids map[string]string, res *provider.ListStorageSpacesResponse, expectedErr error, level string) { + service, logBuf := newLoggedService() + // a nil response stands for a failed request + var transportErr error + if res == nil { + transportErr = errors.New("connection refused") + } + gatewayClient.On("ListStorageSpaces", mock.Anything, mock.Anything).Return(res, transportErr) + + Expect(call(service)).To(MatchError(expectedErr)) + + // the request failed while resolving the space, before delegating to the item method + for _, c := range gatewayClient.Calls { + Expect(c.Method).To(Equal("ListStorageSpaces")) + } + + graphErr, _ := errorcode.ToError(expectedErr) + // the failure is logged with its error code and error text, whatever its level + expected := []gomegatypes.GomegaMatcher{ + HaveKeyWithValue("level", level), + HaveKeyWithValue("errorCode", graphErr.GetCode().String()), + HaveKeyWithValue("error", expectedErr.Error()), + } + for _, k := range []string{"driveID", "permissionID", "itemID"} { + if v, ok := ids[k]; ok { + expected = append(expected, HaveKeyWithValue(k, v)) + } else { + expected = append(expected, Not(HaveKey(k))) + } + } + entries := logEntries(logBuf) + Expect(entries).To(ContainElement(SatisfyAll(expected...))) + for _, payloadKey := range []string{"space", "spaces", "res", "response", "stat.res"} { + Expect(entries).ToNot(ContainElement(HaveKey(payloadKey))) + } + if level == "debug" { + Expect(entries).ToNot(ContainElement(HaveKeyWithValue("level", BeElementOf("error", "warn")))) + } else { + errorEntries := entriesAtLevel(entries, "error") + Expect(errorEntries).To(HaveLen(1)) + } + }, + Entry("SpaceRootInvite: missing space", spaceRootInvite, + map[string]string{"driveID": "1$2"}, missingSpaceResponse, missingSpaceErr, "debug"), + Entry("SpaceRootInvite: internal gateway error", spaceRootInvite, + map[string]string{"driveID": "1$2"}, internalSpaceResponse, internalSpaceErr, "error"), + Entry("SpaceRootInvite: transport error", spaceRootInvite, + map[string]string{"driveID": "1$2"}, nil, transportSpaceErr, "error"), + Entry("ListSpaceRootPermissions: missing space", listSpaceRootPermissions, + map[string]string{"driveID": "1$2"}, missingSpaceResponse, missingSpaceErr, "debug"), + Entry("ListSpaceRootPermissions: internal gateway error", listSpaceRootPermissions, + map[string]string{"driveID": "1$2"}, internalSpaceResponse, internalSpaceErr, "error"), + Entry("DeleteSpaceRootPermission: missing space", deleteSpaceRootPermission, + map[string]string{"driveID": "1$2", "permissionID": "permissionid"}, missingSpaceResponse, missingSpaceErr, "debug"), + Entry("DeleteSpaceRootPermission: internal gateway error", deleteSpaceRootPermission, + map[string]string{"driveID": "1$2", "permissionID": "permissionid"}, internalSpaceResponse, internalSpaceErr, "error"), + Entry("UpdateSpaceRootPermission: missing space", updateSpaceRootPermission, + map[string]string{"driveID": "1$2", "permissionID": "permissionid"}, missingSpaceResponse, missingSpaceErr, "debug"), + Entry("UpdateSpaceRootPermission: internal gateway error", updateSpaceRootPermission, + map[string]string{"driveID": "1$2", "permissionID": "permissionid"}, internalSpaceResponse, internalSpaceErr, "error"), + ) + Describe("Invite", func() { var ( createShareResponse *collaboration.CreateShareResponse @@ -205,6 +611,42 @@ var _ = Describe("DriveItemPermissionsService", func() { Expect(permission.GrantedToV2.User.GetId()).To(Equal("guest@xn--infocorp-o0e.com")) }) + It("logs a failed grantee lookup of a mail share by cause with the item id", func() { + cfg.Commons = &shared.Commons{EnableGuestLinks: true} + service, logBuf := newLoggedService() + + // the share provider returns a regular user as grantee, whose lookup fails in the identity backend + createShareResponse.Share = &collaboration.Share{ + Id: &collaboration.ShareId{OpaqueId: "guest123"}, + Grantee: &provider.Grantee{ + Type: provider.GranteeType_GRANTEE_TYPE_USER, + Id: &provider.Grantee_UserId{UserId: &userpb.UserId{ + OpaqueId: "grantee-id", Type: userpb.UserType_USER_TYPE_PRIMARY, + }}, + }, + } + gatewayClient.On("CreateShare", mock.Anything, mock.Anything).Return(createShareResponse, nil) + gatewayClient.On("GetUser", mock.Anything, mock.Anything).Return(nil, errors.New("connection to guest@example.com refused")) + invite := libregraph.DriveItemInvite{ + Roles: []string{unifiedrole.UnifiedRoleViewerID}, + Recipients: []libregraph.DriveRecipient{{Email: libregraph.PtrString("guest@example.com")}}, + } + + _, err := service.Invite(ctx, driveItemId, invite) + Expect(errorcode.IsErrorCode(err, errorcode.GeneralException)).To(BeTrue()) + + entries := logEntries(logBuf) + errorEntries := entriesAtLevel(entries, "error") + Expect(errorEntries).To(HaveLen(1)) + Expect(errorEntries[0]).To(SatisfyAll( + HaveKeyWithValue("message", "failed to convert guest user id to identity"), + HaveKeyWithValue("itemID", storagespace.FormatResourceID(driveItemId)), + HaveKeyWithValue("recipientType", "mail"), + HaveKeyWithValue("errorCode", "generalException"), + HaveKeyWithValue("error", err.Error()), + )) + }) + It("rejects guest shares when guest invites are disabled by default", func() { driveItemInvite.Recipients = []libregraph.DriveRecipient{ {Email: libregraph.PtrString("guest@example.com")}, @@ -247,6 +689,425 @@ var _ = Describe("DriveItemPermissionsService", func() { Expect(permission.GetRoles()[0]).To(Equal(unifiedrole.UnifiedRoleEditorID)) }) + DescribeTable("logs invite validation failures as debug with the resource ids", + func(setup func() *provider.ResourceId, expectedErr error, ids map[string]string) { + itemID := setup() + service, logBuf := newLoggedService() + + _, err := service.Invite(ctx, itemID, driveItemInvite) + Expect(err).To(MatchError(expectedErr)) + // validation failed before anything was shared + gatewayClient.AssertNotCalled(GinkgoT(), "CreateShare", mock.Anything, mock.Anything) + gatewayClient.AssertNotCalled(GinkgoT(), "CreateOCMShare", mock.Anything, mock.Anything) + + expected := []gomegatypes.GomegaMatcher{ + HaveKeyWithValue("level", "debug"), + HaveKeyWithValue("itemID", storagespace.FormatResourceID(itemID)), + } + for k, v := range ids { + expected = append(expected, HaveKeyWithValue(k, v)) + } + entries := logEntries(logBuf) + Expect(entries).To(ContainElement(SatisfyAll(expected...))) + Expect(entries).ToNot(ContainElement(HaveKeyWithValue("level", BeElementOf("error", "warn")))) + for _, payloadKey := range []string{"invite", "recipient", "recipients", "email", "mail", "Body", "body"} { + Expect(entries).ToNot(ContainElement(HaveKey(payloadKey))) + } + }, + Entry("unsupported resource type", + func() *provider.ResourceId { + statResponse.Info.Type = provider.ResourceType_RESOURCE_TYPE_SYMLINK + driveItemInvite.Roles = []string{unifiedrole.UnifiedRoleViewerID} + driveItemInvite.Recipients = []libregraph.DriveRecipient{ + {ObjectId: libregraph.PtrString("1"), LibreGraphRecipientType: libregraph.PtrString("user")}, + } + return driveItemId + }, + errorcode.New(errorcode.InvalidRequest, "unsupported resource type"), + map[string]string{}), + Entry("unknown or disabled role", + func() *provider.ResourceId { + driveItemInvite.Roles = []string{"unknown-role-id"} + driveItemInvite.Recipients = []libregraph.DriveRecipient{ + {ObjectId: libregraph.PtrString("1"), LibreGraphRecipientType: libregraph.PtrString("user")}, + } + return driveItemId + }, + unifiedrole.ErrUnknownRole, + map[string]string{"roleID": "unknown-role-id"}), + Entry("enabled role without a definition", + func() *provider.ResourceId { + // the failing role is not the first requested one + cfg.UnifiedRoles.AvailableRoles = append(cfg.UnifiedRoles.AvailableRoles, "undefined-role-id") + driveItemInvite.Roles = []string{unifiedrole.UnifiedRoleViewerID, "undefined-role-id"} + driveItemInvite.Recipients = []libregraph.DriveRecipient{ + {ObjectId: libregraph.PtrString("1"), LibreGraphRecipientType: libregraph.PtrString("user")}, + } + return driveItemId + }, + unifiedrole.ErrUnknownRole, + map[string]string{"roleID": "undefined-role-id"}), + Entry("role not applicable to the resource", + func() *provider.ResourceId { + driveItemInvite.Roles = []string{unifiedrole.UnifiedRoleManagerID} + driveItemInvite.Recipients = []libregraph.DriveRecipient{ + {ObjectId: libregraph.PtrString("1"), LibreGraphRecipientType: libregraph.PtrString("user")}, + } + return driveItemId + }, + errorcode.New(errorcode.InvalidRequest, "role not applicable to this resource"), + map[string]string{"roleID": unifiedrole.UnifiedRoleManagerID}), + Entry("mail sharing disabled", + func() *provider.ResourceId { + driveItemInvite.Roles = []string{unifiedrole.UnifiedRoleViewerID} + driveItemInvite.Recipients = []libregraph.DriveRecipient{ + {Email: libregraph.PtrString("guest@example.com")}, + } + return driveItemId + }, + errorcode.New(errorcode.NotSupported, "sharing with mail recipients is not enabled"), + map[string]string{}), + Entry("federated user invited as a space member", + func() *provider.ResourceId { + cfg.IncludeOCMSharees = true + spaceRootID := &provider.ResourceId{StorageId: "1", SpaceId: "2", OpaqueId: "2"} + statResponse.Info = &provider.ResourceInfo{ + Id: spaceRootID, + Type: provider.ResourceType_RESOURCE_TYPE_CONTAINER, + Space: &provider.StorageSpace{Root: spaceRootID}, + } + gatewayClient.On("GetUser", mock.Anything, mock.Anything).Return(&userpb.GetUserResponse{ + Status: status.NewNotFound(ctx, "user not found"), + }, nil) + gatewayClient.On("GetAcceptedUser", mock.Anything, mock.Anything).Return(&invitepb.GetAcceptedUserResponse{ + Status: status.NewOK(ctx), + RemoteUser: &userpb.User{ + Id: &userpb.UserId{OpaqueId: "remote", Idp: "ocm.example.org", Type: userpb.UserType_USER_TYPE_FEDERATED}, + }, + }, nil) + driveItemInvite.Roles = []string{unifiedrole.UnifiedRoleSpaceViewerID} + driveItemInvite.Recipients = []libregraph.DriveRecipient{ + {ObjectId: libregraph.PtrString("remote@ocm.example.org"), LibreGraphRecipientType: libregraph.PtrString("user")}, + } + return spaceRootID + }, + errorcode.New(errorcode.InvalidRequest, "federated user can not become a space member"), + map[string]string{}), + ) + + DescribeTable("logs invite recipient lookup failures by cause with the item id", + func(recipientType string, setup func(), expectedErr error, level string) { + setup() + service, logBuf := newLoggedService() + driveItemInvite.Roles = []string{unifiedrole.UnifiedRoleViewerID} + driveItemInvite.Recipients = []libregraph.DriveRecipient{ + {ObjectId: libregraph.PtrString("recipient-id-42"), LibreGraphRecipientType: libregraph.PtrString(recipientType)}, + } + + _, err := service.Invite(ctx, driveItemId, driveItemInvite) + Expect(err).To(MatchError(expectedErr)) + // nothing is shared after the failed lookup + gatewayClient.AssertNotCalled(GinkgoT(), "CreateShare", mock.Anything, mock.Anything) + gatewayClient.AssertNotCalled(GinkgoT(), "CreateOCMShare", mock.Anything, mock.Anything) + + entries := logEntries(logBuf) + // the failure is logged with the error text of the lookup, whatever its level + Expect(entries).To(ContainElement(SatisfyAll( + HaveKeyWithValue("level", level), + HaveKeyWithValue("itemID", storagespace.FormatResourceID(driveItemId)), + HaveKeyWithValue("recipientType", recipientType), + HaveKey("error"), + ))) + if level == "debug" { + Expect(entries).ToNot(ContainElement(HaveKeyWithValue("level", BeElementOf("error", "warn")))) + } else { + Expect(entriesAtLevel(entries, "error")).To(HaveLen(1)) + } + for _, payloadKey := range []string{"objectID", "groupId", "userId", "recipient", "recipients", "invite", "Body", "body"} { + Expect(entries).ToNot(ContainElement(HaveKey(payloadKey))) + } + }, + Entry("A: group not found", "group", + func() { + gatewayClient.On("GetGroup", mock.Anything, mock.Anything).Return(&grouppb.GetGroupResponse{ + Status: status.NewNotFound(ctx, "group recipient-id-42 not found"), + }, nil) + }, + errorcode.New(errorcode.InvalidRequest, "itemNotFound: not found"), "debug"), + Entry("B: group lookup backend failure", "group", + func() { + gatewayClient.On("GetGroup", mock.Anything, mock.Anything).Return(&grouppb.GetGroupResponse{ + Status: status.NewInternal(ctx, "lookup of recipient-id-42 failed"), + }, nil) + }, + errorcode.New(errorcode.InvalidRequest, "generalException: lookup of recipient-id-42 failed"), "error"), + Entry("C: user not found", "user", + func() { + gatewayClient.On("GetUser", mock.Anything, mock.Anything).Return(&userpb.GetUserResponse{ + Status: status.NewNotFound(ctx, "user recipient-id-42 not found"), + }, nil) + }, + errorcode.New(errorcode.InvalidRequest, "itemNotFound: not found"), "debug"), + Entry("D: user lookup backend failure", "user", + func() { + gatewayClient.On("GetUser", mock.Anything, mock.Anything).Return(&userpb.GetUserResponse{ + Status: status.NewInternal(ctx, "lookup of recipient-id-42 failed"), + }, nil) + }, + errorcode.New(errorcode.InvalidRequest, "generalException: unexpected status code while getting user: CODE_INTERNAL"), "error"), + ) + + DescribeTable("logs invite share creation failures by cause with the item id", + func(recipientType string, setup func(), expectedErr error, level string) { + setup() + service, logBuf := newLoggedService() + driveItemInvite.Roles = []string{unifiedrole.UnifiedRoleViewerID} + + _, err := service.Invite(ctx, driveItemId, driveItemInvite) + Expect(err).To(MatchError(expectedErr)) + // the share creation was attempted + gatewayClient.AssertCalled(GinkgoT(), "CreateShare", mock.Anything, mock.Anything) + + entries := logEntries(logBuf) + var creationEntries []map[string]any + for _, entry := range entries { + if entry["level"] == level && entry["itemID"] == storagespace.FormatResourceID(driveItemId) && entry["recipientType"] == recipientType { + creationEntries = append(creationEntries, entry) + } + } + Expect(creationEntries).To(HaveLen(1)) + // the failure is logged with its error text, whatever its level + Expect(creationEntries[0]).To(HaveKeyWithValue("error", expectedErr.Error())) + if level == "error" { + Expect(entriesAtLevel(entries, "error")).To(HaveLen(1)) + } else { + Expect(entries).ToNot(ContainElement(HaveKeyWithValue("level", BeElementOf("error", "warn")))) + } + for _, payloadKey := range []string{"objectID", "groupId", "userId", "email", "mail", "recipient", "recipients", "share", "invite", "Body", "body"} { + Expect(entries).ToNot(ContainElement(HaveKey(payloadKey))) + } + }, + Entry("A: mail recipient, internal error", "mail", + func() { + cfg.Commons = &shared.Commons{EnableGuestLinks: true} + driveItemInvite.Recipients = []libregraph.DriveRecipient{{Email: libregraph.PtrString("guest@example.com")}} + gatewayClient.On("CreateShare", mock.Anything, mock.Anything).Return(&collaboration.CreateShareResponse{ + Status: status.NewInternal(ctx, "could not share with guest@example.com"), + }, nil) + }, + errorcode.New(errorcode.GeneralException, "could not share with guest@example.com").WithOrigin(errorcode.ErrorOriginCS3), "error"), + Entry("B: group recipient, internal error", "group", + func() { + driveItemInvite.Recipients = []libregraph.DriveRecipient{ + {ObjectId: libregraph.PtrString("recipient-id-42"), LibreGraphRecipientType: libregraph.PtrString("group")}, + } + gatewayClient.On("GetGroup", mock.Anything, mock.Anything).Return(getGroupResponse, nil) + gatewayClient.On("CreateShare", mock.Anything, mock.Anything).Return(&collaboration.CreateShareResponse{ + Status: status.NewInternal(ctx, "could not share with recipient-id-42"), + }, nil) + }, + errorcode.New(errorcode.GeneralException, "could not share with recipient-id-42").WithOrigin(errorcode.ErrorOriginCS3), "error"), + Entry("C: user recipient, internal error", "user", + func() { + driveItemInvite.Recipients = []libregraph.DriveRecipient{ + {ObjectId: libregraph.PtrString("recipient-id-42"), LibreGraphRecipientType: libregraph.PtrString("user")}, + } + gatewayClient.On("GetUser", mock.Anything, mock.Anything).Return(getUserResponse, nil) + gatewayClient.On("CreateShare", mock.Anything, mock.Anything).Return(&collaboration.CreateShareResponse{ + Status: status.NewInternal(ctx, "could not share with recipient-id-42"), + }, nil) + }, + errorcode.New(errorcode.GeneralException, "could not share with recipient-id-42").WithOrigin(errorcode.ErrorOriginCS3), "error"), + Entry("D: user recipient, share already exists", "user", + func() { + driveItemInvite.Recipients = []libregraph.DriveRecipient{ + {ObjectId: libregraph.PtrString("recipient-id-42"), LibreGraphRecipientType: libregraph.PtrString("user")}, + } + gatewayClient.On("GetUser", mock.Anything, mock.Anything).Return(getUserResponse, nil) + gatewayClient.On("CreateShare", mock.Anything, mock.Anything).Return(&collaboration.CreateShareResponse{ + Status: status.NewAlreadyExists(ctx, nil, "share with recipient-id-42 already exists"), + }, nil) + }, + errorcode.New(errorcode.NameAlreadyExists, "share with recipient-id-42 already exists").WithOrigin(errorcode.ErrorOriginCS3), "debug"), + ) + + DescribeTable("logs invite ocm failures by cause with the item id", + func(setup func(), attempted string, expectedErr error, level string) { + // a federated recipient, found via the accepted user fallback, on a regular item + cfg.IncludeOCMSharees = true + gatewayClient.On("GetUser", mock.Anything, mock.Anything).Return(&userpb.GetUserResponse{ + Status: status.NewNotFound(ctx, "user not found"), + }, nil) + gatewayClient.On("GetAcceptedUser", mock.Anything, mock.Anything).Return(&invitepb.GetAcceptedUserResponse{ + Status: status.NewOK(ctx), + RemoteUser: &userpb.User{ + Id: &userpb.UserId{OpaqueId: "remote", Idp: "ocm.example.org", Type: userpb.UserType_USER_TYPE_FEDERATED}, + }, + }, nil) + setup() + service, logBuf := newLoggedService() + driveItemInvite.Roles = []string{unifiedrole.UnifiedRoleViewerID} + driveItemInvite.Recipients = []libregraph.DriveRecipient{ + {ObjectId: libregraph.PtrString("remote@ocm.example.org"), LibreGraphRecipientType: libregraph.PtrString("user")}, + } + + _, err := service.Invite(ctx, driveItemId, driveItemInvite) + Expect(err).To(MatchError(expectedErr)) + // the failing ocm operation was attempted, nothing else was shared + gatewayClient.AssertCalled(GinkgoT(), attempted, mock.Anything, mock.Anything) + gatewayClient.AssertNotCalled(GinkgoT(), "CreateShare", mock.Anything, mock.Anything) + + entries := logEntries(logBuf) + var ocmEntries []map[string]any + for _, entry := range entries { + if entry["level"] == level && entry["itemID"] == storagespace.FormatResourceID(driveItemId) && entry["recipientType"] == "ocm" { + ocmEntries = append(ocmEntries, entry) + } + } + Expect(ocmEntries).To(HaveLen(1)) + // the failure is logged with its error text, whatever its level + Expect(ocmEntries[0]).To(HaveKeyWithValue("error", expectedErr.Error())) + if level == "error" { + Expect(entriesAtLevel(entries, "error")).To(HaveLen(1)) + } else { + Expect(entries).ToNot(ContainElement(HaveKeyWithValue("level", BeElementOf("error", "warn")))) + } + for _, payloadKey := range []string{"objectID", "userId", "domain", "provider", "share", "recipient", "recipients", "invite", "Body", "body"} { + Expect(entries).ToNot(ContainElement(HaveKey(payloadKey))) + } + }, + Entry("A: provider info lookup, internal error", + func() { + gatewayClient.On("GetInfoByDomain", mock.Anything, mock.Anything).Return(&ocmprovider.GetInfoByDomainResponse{ + Status: status.NewInternal(ctx, "no provider info for ocm.example.org"), + }, nil) + }, + "GetInfoByDomain", + errorcode.New(errorcode.GeneralException, "no provider info for ocm.example.org").WithOrigin(errorcode.ErrorOriginCS3), "error"), + Entry("B: ocm share creation, internal error", + func() { + gatewayClient.On("GetInfoByDomain", mock.Anything, mock.Anything).Return(&ocmprovider.GetInfoByDomainResponse{ + Status: status.NewOK(ctx), + ProviderInfo: &ocmprovider.ProviderInfo{Domain: "ocm.example.org"}, + }, nil) + gatewayClient.On("CreateOCMShare", mock.Anything, mock.Anything).Return(&ocm.CreateOCMShareResponse{ + Status: status.NewInternal(ctx, "could not share with remote@ocm.example.org"), + }, nil) + }, + "CreateOCMShare", + errorcode.New(errorcode.GeneralException, "could not share with remote@ocm.example.org").WithOrigin(errorcode.ErrorOriginCS3), "error"), + Entry("C: ocm share creation, share already exists", + func() { + gatewayClient.On("GetInfoByDomain", mock.Anything, mock.Anything).Return(&ocmprovider.GetInfoByDomainResponse{ + Status: status.NewOK(ctx), + ProviderInfo: &ocmprovider.ProviderInfo{Domain: "ocm.example.org"}, + }, nil) + gatewayClient.On("CreateOCMShare", mock.Anything, mock.Anything).Return(&ocm.CreateOCMShareResponse{ + Status: status.NewAlreadyExists(ctx, nil, "share with remote@ocm.example.org already exists"), + }, nil) + }, + "CreateOCMShare", + errorcode.New(errorcode.NameAlreadyExists, "share with remote@ocm.example.org already exists").WithOrigin(errorcode.ErrorOriginCS3), "debug"), + ) + + DescribeTable("marks the Invite span by the cause of a failed identity lookup", + func(recipientType string, setup func(), wantStatus codes.Code, wantDescription string) { + sr, tp := newSpanRecorder() + service, err := svc.NewDriveItemPermissionsService(log.NewLogger(), gatewaySelector, cache, cfg, tp) + Expect(err).ToNot(HaveOccurred()) + setup() + invite := libregraph.DriveItemInvite{ + Roles: []string{unifiedrole.UnifiedRoleViewerID}, + Recipients: []libregraph.DriveRecipient{ + {ObjectId: libregraph.PtrString("1"), LibreGraphRecipientType: libregraph.PtrString(recipientType)}, + }, + } + + _, err = service.Invite(ctx, driveItemId, invite) + // the identity lookup failure is still returned as invalid request + Expect(errorcode.IsErrorCode(err, errorcode.InvalidRequest)).To(BeTrue()) + + var span sdktrace.ReadOnlySpan + for _, s := range sr.Ended() { + if s.Name() == "Invite" { + span = s + } + } + Expect(span).ToNot(BeNil()) + Expect(span.Status().Code).To(Equal(wantStatus)) + Expect(span.Status().Description).To(Equal(wantDescription)) + Expect(span.Attributes()).To(ContainElement(attribute.String("error.type", "invalidRequest"))) + Expect(span.Events()).To(BeEmpty()) + // backend identity text never reaches the span + raw, err := json.Marshal([]any{span.Status(), span.Attributes()}) + Expect(err).ToNot(HaveOccurred()) + Expect(string(raw)).ToNot(ContainSubstring("alice@example.com")) + }, + Entry("recipient not found", "user", func() { + gatewayClient.On("GetUser", mock.Anything, mock.Anything).Return(&userpb.GetUserResponse{ + Status: status.NewNotFound(ctx, "alice@example.com not found"), + }, nil) + }, codes.Unset, ""), + Entry("recipient lookup backend failure", "user", func() { + gatewayClient.On("GetUser", mock.Anything, mock.Anything).Return(nil, errors.New("connection to alice@example.com refused")) + }, codes.Error, "generalException"), + Entry("group recipient lookup backend failure", "group", func() { + gatewayClient.On("GetGroup", mock.Anything, mock.Anything).Return(&grouppb.GetGroupResponse{ + Status: status.NewInternal(ctx, "lookup of alice@example.com failed"), + }, nil) + }, codes.Error, "generalException"), + Entry("inviter lookup backend failure", "user", func() { + gatewayClient.On("GetUser", mock.Anything, mock.MatchedBy(func(req *userpb.GetUserRequest) bool { + return req.GetUserId().GetOpaqueId() == "1" + })).Return(getUserResponse, nil) + createShareResponse.Share = &collaboration.Share{Id: &collaboration.ShareId{OpaqueId: "123"}} + gatewayClient.On("CreateShare", mock.Anything, mock.Anything).Return(createShareResponse, nil) + gatewayClient.On("GetUser", mock.Anything, mock.MatchedBy(func(req *userpb.GetUserRequest) bool { + return req.GetUserId().GetOpaqueId() == currentUser.GetId().GetOpaqueId() + })).Return(nil, errors.New("connection to alice@example.com refused")) + }, codes.Error, "generalException"), + ) + + It("logs a failed inviter identity lookup as error with the item id and the error text", func() { + service, logBuf := newLoggedService() + + // the recipient is found and the share is created ... + gatewayClient.On("GetUser", mock.Anything, mock.MatchedBy(func(req *userpb.GetUserRequest) bool { + return req.GetUserId().GetOpaqueId() == "1" + })).Return(getUserResponse, nil) + createShareResponse.Share = &collaboration.Share{Id: &collaboration.ShareId{OpaqueId: "123"}} + gatewayClient.On("CreateShare", mock.Anything, mock.Anything).Return(createShareResponse, nil) + // ... but the lookup of the inviting user fails afterwards + gatewayClient.On("GetUser", mock.Anything, mock.MatchedBy(func(req *userpb.GetUserRequest) bool { + return req.GetUserId().GetOpaqueId() == currentUser.GetId().GetOpaqueId() + })).Return(nil, errors.New("connection to inviter@example.com refused")) + driveItemInvite.Roles = []string{unifiedrole.UnifiedRoleViewerID} + driveItemInvite.Recipients = []libregraph.DriveRecipient{ + {ObjectId: libregraph.PtrString("1"), LibreGraphRecipientType: libregraph.PtrString("user")}, + } + + _, err := service.Invite(ctx, driveItemId, driveItemInvite) + Expect(err).To(MatchError(errorcode.New(errorcode.InvalidRequest, "generalException: connection to inviter@example.com refused"))) + // the share was created before the inviter lookup, as in the existing control flow + gatewayClient.AssertCalled(GinkgoT(), "CreateShare", mock.Anything, mock.Anything) + gatewayClient.AssertCalled(GinkgoT(), "GetUser", mock.Anything, mock.MatchedBy(func(req *userpb.GetUserRequest) bool { + return req.GetUserId().GetOpaqueId() == currentUser.GetId().GetOpaqueId() + })) + + entries := logEntries(logBuf) + errorEntries := entriesAtLevel(entries, "error") + Expect(errorEntries).To(HaveLen(1)) + Expect(errorEntries[0]).To(SatisfyAll( + HaveKeyWithValue("itemID", storagespace.FormatResourceID(driveItemId)), + // the cause of the failed lookup, with its error text + HaveKeyWithValue("errorCode", "generalException"), + HaveKeyWithValue("error", "generalException: connection to inviter@example.com refused"), + )) + for _, payloadKey := range []string{"userId", "userID", "objectID", "user", "invite", "share", "Body", "body"} { + Expect(entries).ToNot(ContainElement(HaveKey(payloadKey))) + } + }) + It("fails with when trying to set a space role on a file", func() { driveItemInvite.Recipients = []libregraph.DriveRecipient{ {ObjectId: libregraph.PtrString("1"), LibreGraphRecipientType: libregraph.PtrString("user")}, @@ -313,7 +1174,7 @@ var _ = Describe("DriveItemPermissionsService", func() { // SecureViewer is enabled in ci, we need to remove it in the unit test return s != unifiedrole.UnifiedRoleSecureViewerID }) - service, err := svc.NewDriveItemPermissionsService(log.NewLogger(), gatewaySelector, cache, cfg) + service, err := svc.NewDriveItemPermissionsService(log.NewLogger(), gatewaySelector, cache, cfg, nil) Expect(err).ToNot(HaveOccurred()) driveItemInvite.Roles = []string{unifiedrole.UnifiedRoleViewerID, unifiedrole.UnifiedRoleSecureViewerID} @@ -393,6 +1254,49 @@ var _ = Describe("DriveItemPermissionsService", func() { Expect(permission.GrantedToV2.User.GetDisplayName()).To(Equal(getUserResponse.User.DisplayName)) Expect(permission.GrantedToV2.User.GetId()).To(Equal("1")) }) + It("records a SpaceRootInvite span as the parent of the Invite span", func() { + sr, tp := newSpanRecorder() + service, err := svc.NewDriveItemPermissionsService(log.NewLogger(), gatewaySelector, cache, cfg, tp) + Expect(err).ToNot(HaveOccurred()) + + listSpacesResponse.StorageSpaces[0].SpaceType = "project" + listSpacesResponse.StorageSpaces[0].Root = &provider.ResourceId{ + StorageId: "1", + SpaceId: "2", + OpaqueId: "3", + } + statResponse.Info.Id = listSpacesResponse.StorageSpaces[0].Root + statResponse.Info.Space = &provider.StorageSpace{ + Root: listSpacesResponse.StorageSpaces[0].Root, + } + gatewayClient.On("ListStorageSpaces", mock.Anything, mock.Anything).Return(listSpacesResponse, nil) + gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(statResponse, nil) + gatewayClient.On("GetUser", mock.Anything, mock.Anything).Return(getUserResponse, nil) + gatewayClient.On("CreateShare", mock.Anything, mock.Anything).Return(createShareResponse, nil) + driveItemInvite.Recipients = []libregraph.DriveRecipient{ + {ObjectId: libregraph.PtrString("1"), LibreGraphRecipientType: libregraph.PtrString("user")}, + } + createShareResponse.Share = &collaboration.Share{Id: &collaboration.ShareId{OpaqueId: "123"}} + + permission, err := service.SpaceRootInvite(ctx, driveId, driveItemInvite) + Expect(err).ToNot(HaveOccurred()) + // the space was resolved and the call was delegated to Invite, which created the share + Expect(permission.GetId()).To(Equal("123")) + gatewayClient.AssertCalled(GinkgoT(), "CreateShare", mock.Anything, mock.Anything) + + spans := map[string]sdktrace.ReadOnlySpan{} + for _, s := range sr.Ended() { + spans[s.Name()] = s + } + Expect(spans).To(HaveKey("SpaceRootInvite")) + Expect(spans).To(HaveKey("Invite")) + parent := spans["SpaceRootInvite"].SpanContext() + child := spans["Invite"] + Expect(parent.IsValid()).To(BeTrue()) + Expect(child.SpanContext().IsValid()).To(BeTrue()) + Expect(child.Parent().SpanID()).To(Equal(parent.SpanID())) + Expect(child.SpanContext().TraceID()).To(Equal(parent.TraceID())) + }) It("rejects to add a user to a personal space", func() { gatewayClient.On("ListStorageSpaces", mock.Anything, mock.Anything).Return(listSpacesResponse, nil) driveItemInvite.Recipients = []libregraph.DriveRecipient{ @@ -431,6 +1335,365 @@ var _ = Describe("DriveItemPermissionsService", func() { PermissionSet: roleconversions.NewViewerRole().CS3ResourcePermissions(), } }) + It("logs a share listing failure once as error with the item id", func() { + service, logBuf := newLoggedService() + + gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(statResponse, nil) + gatewayClient.On("ListShares", mock.Anything, mock.Anything).Return(&collaboration.ListSharesResponse{ + Status: status.NewInternal(context.Background(), "share manager unavailable"), + }, nil) + + _, err := service.ListPermissions(ctx, itemID, svc.ListPermissionsQueryOptions{}) + Expect(err).To(MatchError(errorcode.New(errorcode.GeneralException, "share manager unavailable"))) + // listing stops at the failed user share lookup + gatewayClient.AssertNotCalled(GinkgoT(), "ListPublicShares", mock.Anything, mock.Anything) + + entries := logEntries(logBuf) + errorEntries := entriesAtLevel(entries, "error") + Expect(errorEntries).To(HaveLen(1)) + Expect(errorEntries[0]).To(SatisfyAll( + HaveKeyWithValue("message", "could not list user shares"), + HaveKeyWithValue("itemID", storagespace.FormatResourceID(itemID)), + HaveKeyWithValue("error", err.Error()), + HaveKeyWithValue("errorCode", "generalException"), + )) + for _, payloadKey := range []string{"shares", "share", "res", "response", "stat.res"} { + Expect(entries).ToNot(ContainElement(HaveKey(payloadKey))) + } + }) + // spaceRootSharesRequest matches a share listing request for space root (or regular) shares only + spaceRootSharesRequest := func(spaceRoot bool) any { + return mock.MatchedBy(func(req *collaboration.ListSharesRequest) bool { + return slices.ContainsFunc(req.GetFilters(), func(f *collaboration.Filter) bool { + return f.GetType() == collaboration.Filter_TYPE_SPACE_ROOT && f.GetSpaceRoot() == spaceRoot + }) + }) + } + DescribeTable("logs the identity backend error when a share grantee lookup fails", + func(setup func(groupGrantee *provider.Grantee) *provider.ResourceId, listingMethod string) { + groupGrantee := &provider.Grantee{ + Type: provider.GranteeType_GRANTEE_TYPE_GROUP, + Id: &provider.Grantee_GroupId{GroupId: &grouppb.GroupId{OpaqueId: "groupid"}}, + } + listedItemID := setup(groupGrantee) + service, logBuf := newLoggedService() + + const identityBackendMessage = "ldap search failed for cn=private-group-dn-42,ou=groups" + gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(statResponse, nil) + gatewayClient.On("GetGroup", mock.Anything, mock.Anything).Return(&grouppb.GetGroupResponse{ + Status: status.NewInternal(context.Background(), identityBackendMessage), + }, nil) + + _, err := service.ListPermissions(ctx, listedItemID, svc.ListPermissionsQueryOptions{}) + // the returned error is unchanged: the share conversion error wrapped by the listing + Expect(err).To(MatchError(errorcode.New(errorcode.GeneralException, + errorcode.New(errorcode.GeneralException, + errorcode.New(errorcode.GeneralException, identityBackendMessage).Error()).Error()))) + // the shares were listed and the group grantee was looked up, listing stops before the public shares + gatewayClient.AssertCalled(GinkgoT(), listingMethod, mock.Anything, mock.Anything) + gatewayClient.AssertCalled(GinkgoT(), "GetGroup", mock.Anything, mock.MatchedBy(func(req *grouppb.GetGroupRequest) bool { + return req.GetGroupId().GetOpaqueId() == "groupid" + })) + gatewayClient.AssertNotCalled(GinkgoT(), "ListPublicShares", mock.Anything, mock.Anything) + + entries := logEntries(logBuf) + errorEntries := entriesAtLevel(entries, "error") + Expect(errorEntries).To(HaveLen(1)) + Expect(errorEntries[0]).To(SatisfyAll( + HaveKeyWithValue("itemID", storagespace.FormatResourceID(listedItemID)), + HaveKeyWithValue("error", err.Error()), + )) + for _, payloadKey := range []string{"shares", "share", "group", "res", "response", "stat.res"} { + Expect(entries).ToNot(ContainElement(HaveKey(payloadKey))) + } + }, + Entry("user share listing", + func(groupGrantee *provider.Grantee) *provider.ResourceId { + gatewayClient.On("ListShares", mock.Anything, spaceRootSharesRequest(false)).Return(&collaboration.ListSharesResponse{ + Status: status.NewOK(ctx), + Shares: []*collaboration.Share{{ + Id: &collaboration.ShareId{OpaqueId: "groupshareid"}, + ResourceId: itemID, + Grantee: groupGrantee, + Permissions: &collaboration.SharePermissions{Permissions: roleconversions.NewViewerRole().CS3ResourcePermissions()}, + }}, + }, nil) + return itemID + }, + "ListShares", + ), + Entry("space root share listing", + func(groupGrantee *provider.Grantee) *provider.ResourceId { + spaceRootID := &provider.ResourceId{StorageId: "1", SpaceId: "2", OpaqueId: "2"} + statResponse.Info.Id = spaceRootID + statResponse.Info.Type = provider.ResourceType_RESOURCE_TYPE_CONTAINER + statResponse.Info.Space = &provider.StorageSpace{Root: spaceRootID} + gatewayClient.On("ListShares", mock.Anything, spaceRootSharesRequest(true)).Return(&collaboration.ListSharesResponse{ + Status: status.NewOK(ctx), + Shares: []*collaboration.Share{{ + Id: &collaboration.ShareId{OpaqueId: "groupshareid"}, + ResourceId: spaceRootID, + Grantee: groupGrantee, + Permissions: &collaboration.SharePermissions{Permissions: roleconversions.NewSpaceViewerRole().CS3ResourcePermissions()}, + }}, + }, nil) + return spaceRootID + }, + "ListShares", + ), + Entry("ocm share listing", + func(groupGrantee *provider.Grantee) *provider.ResourceId { + cfg.IncludeOCMSharees = true + gatewayClient.On("ListShares", mock.Anything, mock.Anything).Return(listSharesResponse, nil) + gatewayClient.On("ListOCMShares", mock.Anything, mock.Anything).Return(&ocm.ListOCMSharesResponse{ + Status: status.NewOK(ctx), + Shares: []*ocm.Share{{ + Id: &ocm.ShareId{OpaqueId: "ocmgroupshareid"}, + ResourceId: itemID, + Grantee: groupGrantee, + }}, + }, nil) + return itemID + }, + "ListOCMShares", + ), + ) + It("logs an unsupported resource type as debug with the item id", func() { + service, logBuf := newLoggedService() + + // neither a space root, nor a folder, nor a file + statResponse.Info.Type = provider.ResourceType_RESOURCE_TYPE_SYMLINK + gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(statResponse, nil) + + _, err := service.ListPermissions(ctx, itemID, svc.ListPermissionsQueryOptions{}) + Expect(err).To(MatchError(errorcode.New(errorcode.InvalidRequest, "unsupported resource type"))) + // no shares are listed after the validation failed + for _, method := range []string{"ListShares", "ListOCMShares", "ListPublicShares"} { + gatewayClient.AssertNotCalled(GinkgoT(), method, mock.Anything, mock.Anything) + } + + entries := logEntries(logBuf) + var debugEntries []map[string]any + for _, entry := range entries { + if entry["level"] == "debug" && entry["itemID"] == storagespace.FormatResourceID(itemID) { + debugEntries = append(debugEntries, entry) + } + } + Expect(debugEntries).To(HaveLen(1)) + Expect(entries).ToNot(ContainElement(HaveKeyWithValue("level", BeElementOf("error", "warn")))) + }) + It("logs a public share listing failure once as error with the item id", func() { + service, logBuf := newLoggedService() + + gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(statResponse, nil) + gatewayClient.On("ListShares", mock.Anything, mock.Anything).Return(listSharesResponse, nil) + gatewayClient.On("ListPublicShares", mock.Anything, mock.Anything).Return(&link.ListPublicSharesResponse{ + Status: status.NewInternal(context.Background(), "listing failed for /Users/alice/Private/salary-2026.ods"), + }, nil) + + _, err := service.ListPermissions(ctx, itemID, svc.ListPermissionsQueryOptions{}) + Expect(err).To(MatchError(errorcode.New(errorcode.GeneralException, "listing failed for /Users/alice/Private/salary-2026.ods"))) + // user shares were listed before the public share lookup failed + gatewayClient.AssertCalled(GinkgoT(), "ListShares", mock.Anything, mock.Anything) + gatewayClient.AssertCalled(GinkgoT(), "ListPublicShares", mock.Anything, mock.Anything) + + entries := logEntries(logBuf) + errorEntries := entriesAtLevel(entries, "error") + Expect(errorEntries).To(HaveLen(1)) + Expect(errorEntries[0]).To(SatisfyAll( + HaveKeyWithValue("message", "could not list public shares"), + HaveKeyWithValue("itemID", storagespace.FormatResourceID(itemID)), + HaveKeyWithValue("errorCode", "generalException"), + HaveKeyWithValue("error", err.Error()), + )) + for _, payloadKey := range []string{"shares", "share", "Link", "res", "response"} { + Expect(entries).ToNot(ContainElement(HaveKey(payloadKey))) + } + }) + It("logs a gateway selection failure while listing public shares as error in the helper and the operation with the item id", func() { + gatewayErr := errors.New("no gateway available") + // ListPermissions and the user share listing get a client, the public share listing does not + gatewaySelector.EXPECT().Next().Unset() + gatewaySelector.EXPECT().Next().Return(gatewayClient, nil).Times(2) + gatewaySelector.EXPECT().Next().Return(nil, gatewayErr).Times(1) + service, logBuf := newLoggedService() + gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(statResponse, nil) + gatewayClient.On("ListShares", mock.Anything, mock.Anything).Return(listSharesResponse, nil) + + _, err := service.ListPermissions(ctx, itemID, svc.ListPermissionsQueryOptions{}) + Expect(err).To(MatchError(errorcode.New(errorcode.GeneralException, gatewayErr.Error()))) + // user shares were listed, listing stops at the public share lookup + gatewayClient.AssertCalled(GinkgoT(), "ListShares", mock.Anything, mock.Anything) + gatewayClient.AssertNotCalled(GinkgoT(), "ListPublicShares", mock.Anything, mock.Anything) + + // the helper and the operation both log the reason, the operation with the item id and the error code + Expect(entriesAtLevel(logEntries(logBuf), "error")).To(ConsistOf( + gatewayHelperEntry("could not select next gateway client", gatewayErr.Error()), + SatisfyAll( + HaveKeyWithValue("message", "could not list public shares"), + HaveKeyWithValue("itemID", storagespace.FormatResourceID(itemID)), + HaveKeyWithValue("errorCode", "generalException"), + HaveKeyWithValue("error", err.Error()), + ), + )) + }) + It("logs an ocm share listing failure once as error with the item id", func() { + cfg.IncludeOCMSharees = true + service, logBuf := newLoggedService() + + gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(statResponse, nil) + gatewayClient.On("ListShares", mock.Anything, mock.Anything).Return(listSharesResponse, nil) + gatewayClient.On("ListOCMShares", mock.Anything, mock.Anything).Return(&ocm.ListOCMSharesResponse{ + Status: status.NewInternal(context.Background(), "ocm share manager unavailable"), + }, nil) + + _, err := service.ListPermissions(ctx, itemID, svc.ListPermissionsQueryOptions{}) + Expect(err).To(MatchError(errorcode.New(errorcode.GeneralException, "ocm share manager unavailable"))) + // listing stops at the failed ocm share lookup + gatewayClient.AssertCalled(GinkgoT(), "ListOCMShares", mock.Anything, mock.Anything) + gatewayClient.AssertNotCalled(GinkgoT(), "ListPublicShares", mock.Anything, mock.Anything) + + entries := logEntries(logBuf) + errorEntries := entriesAtLevel(entries, "error") + Expect(errorEntries).To(HaveLen(1)) + Expect(errorEntries[0]).To(SatisfyAll( + HaveKeyWithValue("message", "could not list ocm shares"), + HaveKeyWithValue("itemID", storagespace.FormatResourceID(itemID)), + HaveKeyWithValue("error", err.Error()), + )) + for _, payloadKey := range []string{"shares", "share", "res", "response"} { + Expect(entries).ToNot(ContainElement(HaveKey(payloadKey))) + } + }) + It("logs a gateway selection failure while listing ocm shares as error in the helper and the operation with the item id", func() { + gatewayErr := errors.New("no gateway available") + cfg.IncludeOCMSharees = true + // ListPermissions and the user share listing get a client, the ocm share listing does not + gatewaySelector.EXPECT().Next().Unset() + gatewaySelector.EXPECT().Next().Return(gatewayClient, nil).Times(2) + gatewaySelector.EXPECT().Next().Return(nil, gatewayErr).Times(1) + service, logBuf := newLoggedService() + gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(statResponse, nil) + gatewayClient.On("ListShares", mock.Anything, mock.Anything).Return(listSharesResponse, nil) + + _, err := service.ListPermissions(ctx, itemID, svc.ListPermissionsQueryOptions{}) + Expect(err).To(MatchError(errorcode.New(errorcode.GeneralException, gatewayErr.Error()))) + // user shares were listed, listing stops at the ocm share lookup + gatewayClient.AssertCalled(GinkgoT(), "ListShares", mock.Anything, mock.Anything) + gatewayClient.AssertNotCalled(GinkgoT(), "ListOCMShares", mock.Anything, mock.Anything) + gatewayClient.AssertNotCalled(GinkgoT(), "ListPublicShares", mock.Anything, mock.Anything) + + // the helper and the operation both log the reason, the operation with the item id and the error code + Expect(entriesAtLevel(logEntries(logBuf), "error")).To(ConsistOf( + gatewayHelperEntry("could not select next gateway client", gatewayErr.Error()), + SatisfyAll( + HaveKeyWithValue("message", "could not list ocm shares"), + HaveKeyWithValue("itemID", storagespace.FormatResourceID(itemID)), + HaveKeyWithValue("error", err.Error()), + ), + )) + }) + It("logs a gateway selection failure while listing shares as error in the helper and the operation with the item id", func() { + gatewayErr := errors.New("no gateway available") + // ListPermissions gets a client, the share listing helper does not + gatewaySelector.EXPECT().Next().Unset() + gatewaySelector.EXPECT().Next().Return(gatewayClient, nil).Times(1) + gatewaySelector.EXPECT().Next().Return(nil, gatewayErr).Times(1) + service, logBuf := newLoggedService() + gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(statResponse, nil) + + _, err := service.ListPermissions(ctx, itemID, svc.ListPermissionsQueryOptions{}) + Expect(err).To(MatchError(errorcode.New(errorcode.GeneralException, gatewayErr.Error()))) + gatewayClient.AssertNotCalled(GinkgoT(), "ListShares", mock.Anything, mock.Anything) + + // the helper and the operation both log the reason, the operation with the item id and the error code + Expect(entriesAtLevel(logEntries(logBuf), "error")).To(ConsistOf( + gatewayHelperEntry("could not select next gateway client", gatewayErr.Error()), + SatisfyAll( + HaveKeyWithValue("message", "could not list user shares"), + HaveKeyWithValue("itemID", storagespace.FormatResourceID(itemID)), + HaveKeyWithValue("error", err.Error()), + ), + )) + }) + It("logs a gateway selection failure while listing space root shares as error in the helper and the operation with the item id", func() { + gatewayErr := errors.New("no gateway available") + spaceRootID := &provider.ResourceId{StorageId: "1", SpaceId: "2", OpaqueId: "2"} + // ListPermissions gets a client, the space root share listing helper does not + gatewaySelector.EXPECT().Next().Unset() + gatewaySelector.EXPECT().Next().Return(gatewayClient, nil).Times(1) + gatewaySelector.EXPECT().Next().Return(nil, gatewayErr).Times(1) + service, logBuf := newLoggedService() + statResponse.Info.Id = spaceRootID + gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(statResponse, nil) + + _, err := service.ListPermissions(ctx, spaceRootID, svc.ListPermissionsQueryOptions{}) + Expect(err).To(MatchError(errorcode.New(errorcode.GeneralException, gatewayErr.Error()))) + // listing stops at the failed space root share lookup + gatewayClient.AssertNotCalled(GinkgoT(), "ListShares", mock.Anything, mock.Anything) + gatewayClient.AssertNotCalled(GinkgoT(), "ListPublicShares", mock.Anything, mock.Anything) + + // the helper and the operation both log the reason, the operation with the item id and the error code + Expect(entriesAtLevel(logEntries(logBuf), "error")).To(ConsistOf( + gatewayHelperEntry("could not select next gateway client", gatewayErr.Error()), + SatisfyAll( + HaveKeyWithValue("message", "could not list space root shares"), + HaveKeyWithValue("itemID", storagespace.FormatResourceID(spaceRootID)), + HaveKeyWithValue("error", err.Error()), + ), + )) + }) + It("records a ListPermissions span", func() { + sr, tp := newSpanRecorder() + service, err := svc.NewDriveItemPermissionsService(log.NewLogger(), gatewaySelector, cache, cfg, tp) + Expect(err).ToNot(HaveOccurred()) + + gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(statResponse, nil) + gatewayClient.On("ListShares", mock.Anything, mock.Anything).Return(listSharesResponse, nil) + gatewayClient.On("ListPublicShares", mock.Anything, mock.Anything).Return(listPublicSharesResponse, nil) + _, err = service.ListPermissions(context.Background(), itemID, svc.ListPermissionsQueryOptions{}) + Expect(err).ToNot(HaveOccurred()) + + Expect(sr.Ended()).To(HaveLen(1)) + span := sr.Ended()[0] + Expect(span.Name()).To(Equal("ListPermissions")) + // a successful operation is neither marked as failed nor carries an error code + Expect(span.Status().Code).To(Equal(codes.Unset)) + for _, attr := range span.Attributes() { + Expect(attr.Key).ToNot(Equal(attribute.Key("error.type"))) + } + }) + It("does not panic and does not record spans without a TraceProvider", func() { + // a recording span from the caller, e.g. the http server span + callerTP := sdktrace.NewTracerProvider() + DeferCleanup(func() { + Expect(callerTP.Shutdown(context.Background())).To(Succeed()) + }) + callerCtx, callerSpan := callerTP.Tracer("test").Start(context.Background(), "caller") + defer callerSpan.End() + + var statCtx context.Context + gatewayClient.On("Stat", mock.Anything, mock.Anything).Run(func(args mock.Arguments) { + statCtx = args.Get(0).(context.Context) + }).Return(statResponse, nil) + gatewayClient.On("ListShares", mock.Anything, mock.Anything).Return(listSharesResponse, nil) + gatewayClient.On("ListPublicShares", mock.Anything, mock.Anything).Return(listPublicSharesResponse, nil) + + Expect(func() { + service, err := svc.NewDriveItemPermissionsService(log.NewLogger(), gatewaySelector, cache, cfg, nil) + Expect(err).ToNot(HaveOccurred()) + _, err = service.ListPermissions(callerCtx, itemID, svc.ListPermissionsQueryOptions{}) + Expect(err).ToNot(HaveOccurred()) + }).NotTo(Panic()) + + // the span active during the gateway call is a non-recording no-op span + // that still carries the caller's span context + Expect(statCtx).ToNot(BeNil()) + active := trace.SpanFromContext(statCtx) + Expect(active.IsRecording()).To(BeFalse()) + Expect(active.SpanContext().TraceID()).To(Equal(callerSpan.SpanContext().TraceID())) + Expect(active.SpanContext().SpanID()).To(Equal(callerSpan.SpanContext().SpanID())) + }) It("populates allowedValues for files that are not shared", func() { gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(statResponse, nil) gatewayClient.On("ListShares", mock.Anything, mock.Anything).Return(listSharesResponse, nil) @@ -537,7 +1800,7 @@ var _ = Describe("DriveItemPermissionsService", func() { cfg = defaults.FullDefaultConfig() cfg.UnifiedRoles.AvailableRoles = []string{unifiedrole.UnifiedRoleViewerID, unifiedrole.UnifiedRoleDeniedID, unifiedrole.UnifiedRoleManagerID} - service, err := svc.NewDriveItemPermissionsService(log.NewLogger(), gatewaySelector, cache, cfg) + service, err := svc.NewDriveItemPermissionsService(log.NewLogger(), gatewaySelector, cache, cfg, nil) gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(statResponse, nil) gatewayClient.On("ListShares", mock.Anything, mock.Anything).Return(listSharesResponse, nil) @@ -745,7 +2008,104 @@ var _ = Describe("DriveItemPermissionsService", func() { Expect(len(permissions.LibreGraphPermissionsActionsAllowedValues)).ToNot(BeZero()) }) + It("records the ListPermissions span as a child of the ListSpaceRootPermissions span", func() { + sr, tp := newSpanRecorder() + service, err := svc.NewDriveItemPermissionsService(log.NewLogger(), gatewaySelector, cache, cfg, tp) + Expect(err).ToNot(HaveOccurred()) + + listSpacesResponse.StorageSpaces[0].SpaceType = "project" + listSpacesResponse.StorageSpaces[0].Root = &provider.ResourceId{ + StorageId: "1", + SpaceId: "2", + OpaqueId: "2", + } + gatewayClient.On("ListStorageSpaces", mock.Anything, mock.Anything).Return(listSpacesResponse, nil) + gatewayClient.On("ListShares", mock.Anything, mock.Anything).Return(&collaboration.ListSharesResponse{Status: status.NewOK(ctx)}, nil) + gatewayClient.On("ListPublicShares", mock.Anything, mock.Anything).Return(listPublicSharesResponse, nil) + statResponse.Info.Id = listSpacesResponse.StorageSpaces[0].Root + gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(statResponse, nil) + _, err = service.ListSpaceRootPermissions(context.Background(), driveId, svc.ListPermissionsQueryOptions{}) + Expect(err).ToNot(HaveOccurred()) + + spans := map[string]sdktrace.ReadOnlySpan{} + for _, s := range sr.Ended() { + spans[s.Name()] = s + } + Expect(spans).To(HaveKey("ListSpaceRootPermissions")) + Expect(spans).To(HaveKey("ListPermissions")) + parent := spans["ListSpaceRootPermissions"].SpanContext() + child := spans["ListPermissions"] + Expect(child.Parent().SpanID()).To(Equal(parent.SpanID())) + Expect(child.SpanContext().TraceID()).To(Equal(parent.TraceID())) + }) }) + Describe("GetPermission", func() { + viewLink := func(id string) *link.PublicShare { + return &link.PublicShare{ + Id: &link.PublicShareId{OpaqueId: id}, + Token: id, + ResourceId: driveItemId, + Permissions: &link.PublicSharePermissions{Permissions: roleconversions.NewViewerRole().CS3ResourcePermissions()}, + } + } + + BeforeEach(func() { + statResponse.Info = &provider.ResourceInfo{ + Id: driveItemId, + Type: provider.ResourceType_RESOURCE_TYPE_FILE, + PermissionSet: roleconversions.NewEditorRole().CS3ResourcePermissions(), + } + }) + + It("returns not found for a permission that is not listed for the item", func() { + // shares are only listed for the requested item; permissions of other resources + // must not be resolved by ID (the strict gateway mock fails on GetShare/GetPublicShare) + gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(statResponse, nil) + gatewayClient.On("ListShares", mock.Anything, mock.MatchedBy(func(req *collaboration.ListSharesRequest) bool { + return slices.ContainsFunc(req.GetFilters(), func(f *collaboration.Filter) bool { + return utils.ResourceIDEqual(f.GetResourceId(), driveItemId) + }) + })).Return(&collaboration.ListSharesResponse{Status: status.NewOK(ctx)}, nil) + listPublicSharesResponse.Share = []*link.PublicShare{viewLink("aaaaaaaaaaaaaaa")} + gatewayClient.On("ListPublicShares", mock.Anything, mock.MatchedBy(func(req *link.ListPublicSharesRequest) bool { + return slices.ContainsFunc(req.GetFilters(), func(f *link.ListPublicSharesRequest_Filter) bool { + return utils.ResourceIDEqual(f.GetResourceId(), driveItemId) + }) + })).Return(listPublicSharesResponse, nil) + + _, err := driveItemPermissionsService.GetPermission(ctx, driveItemId, "ccccccccccccccc") + Expect(errorcode.IsErrorCode(err, errorcode.ItemNotFound)).To(BeTrue()) + }) + + It("propagates stat errors without listing permissions", func() { + statResponse.Status = status.NewPermissionDenied(ctx, nil, "denied") + gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(statResponse, nil) + + _, err := driveItemPermissionsService.GetPermission(ctx, driveItemId, "aaaaaaaaaaaaaaa") + Expect(errorcode.IsErrorCode(err, errorcode.AccessDenied)).To(BeTrue()) + }) + }) + + Describe("GetSpaceRootPermission", func() { + DescribeTable("rejects space types other than project", + func(spaceType string) { + gatewayClient.On("ListStorageSpaces", mock.Anything, mock.Anything).Return(&provider.ListStorageSpacesResponse{ + Status: status.NewOK(ctx), + StorageSpaces: []*provider.StorageSpace{{ + Id: &provider.StorageSpaceId{OpaqueId: "1$2"}, + SpaceType: spaceType, + Root: &provider.ResourceId{StorageId: "1", SpaceId: "2", OpaqueId: "2"}, + }}, + }, nil) + + _, err := driveItemPermissionsService.GetSpaceRootPermission(ctx, &provider.ResourceId{StorageId: "1", SpaceId: "2"}, "aaaaaaaaaaaaaaa") + Expect(err).To(MatchError(errorcode.New(errorcode.InvalidRequest, "unsupported space type"))) + }, + Entry("personal", "personal"), + Entry("virtual", "virtual"), + ) + }) + Describe("DeletePermission", func() { var ( getShareResponse collaboration.GetShareResponse @@ -753,6 +2113,7 @@ var _ = Describe("DriveItemPermissionsService", func() { ) BeforeEach(func() { getPublicShareResponse.Status = status.NewOK(context.Background()) + getPublicShareResponse.Share = nil getShareResponse.Status = status.NewOK(context.Background()) getShareResponse.Share = &collaboration.Share{ Id: &collaboration.ShareId{ @@ -830,6 +2191,287 @@ var _ = Describe("DriveItemPermissionsService", func() { ) Expect(err).ToNot(HaveOccurred()) }) + It("logs a share removal failure once as error with the item and permission ids", func() { + service, logBuf := newLoggedService() + + // not a public link, but a user share whose removal fails + getPublicShareResponse.Status = status.NewNotFound(context.Background(), "") + gatewayClient.On("GetPublicShare", mock.Anything, mock.Anything).Return(&getPublicShareResponse, nil) + gatewayClient.On("GetShare", mock.Anything, mock.Anything).Return(&getShareResponse, nil) + gatewayClient.On("RemoveShare", mock.Anything, mock.Anything).Return(&collaboration.RemoveShareResponse{ + Status: status.NewInternal(context.Background(), "removal failed for /Users/alice/Private/salary-2026.ods"), + }, nil) + + err := service.DeletePermission(ctx, getShareResponse.Share.ResourceId, "permissionid") + Expect(err).To(MatchError(errorcode.New(errorcode.GeneralException, "removal failed for /Users/alice/Private/salary-2026.ods").WithOrigin(errorcode.ErrorOriginCS3))) + gatewayClient.AssertCalled(GinkgoT(), "RemoveShare", mock.Anything, mock.MatchedBy(func(req *collaboration.RemoveShareRequest) bool { + return req.GetRef().GetId().GetOpaqueId() == "permissionid" + })) + + entries := logEntries(logBuf) + errorEntries := entriesAtLevel(entries, "error") + Expect(errorEntries).To(HaveLen(1)) + Expect(errorEntries[0]).To(SatisfyAll( + HaveKeyWithValue("itemID", storagespace.FormatResourceID(getShareResponse.Share.ResourceId)), + HaveKeyWithValue("permissionID", "permissionid"), + HaveKeyWithValue("errorCode", "generalException"), + // the error text tells operators the reason + HaveKeyWithValue("error", err.Error()), + )) + for _, payloadKey := range []string{"share", "res", "response", "request", "Body", "body"} { + Expect(entries).ToNot(ContainElement(HaveKey(payloadKey))) + } + }) + It("logs the error text when resolving a permission fails", func() { + service, logBuf := newLoggedService() + + // not a public link, the user share lookup fails in the share manager + getPublicShareResponse.Status = status.NewNotFound(context.Background(), "") + gatewayClient.On("GetPublicShare", mock.Anything, mock.Anything).Return(&getPublicShareResponse, nil) + gatewayClient.On("GetShare", mock.Anything, mock.Anything).Return(&collaboration.GetShareResponse{ + Status: status.NewInternal(context.Background(), "lookup failed for /Users/alice/Private/salary-2026.ods"), + }, nil) + + err := service.DeletePermission(ctx, getShareResponse.Share.ResourceId, "permissionid") + Expect(err).To(MatchError(errorcode.New(errorcode.GeneralException, "lookup failed for /Users/alice/Private/salary-2026.ods").WithOrigin(errorcode.ErrorOriginCS3))) + gatewayClient.AssertNotCalled(GinkgoT(), "RemoveShare", mock.Anything, mock.Anything) + + entries := logEntries(logBuf) + errorEntries := entriesAtLevel(entries, "error") + Expect(errorEntries).To(HaveLen(1)) + Expect(errorEntries[0]).To(SatisfyAll( + HaveKeyWithValue("message", "could not resolve permission"), + HaveKeyWithValue("itemID", storagespace.FormatResourceID(getShareResponse.Share.ResourceId)), + HaveKeyWithValue("permissionID", "permissionid"), + HaveKeyWithValue("errorCode", "generalException"), + HaveKeyWithValue("error", err.Error()), + )) + }) + DescribeTable("logs permission removal failures by cause with the item and permission ids", + func(setup func() string, expectedErr error, level string) { + removeMethod := setup() + service, logBuf := newLoggedService() + + err := service.DeletePermission(ctx, getShareResponse.Share.ResourceId, "permissionid") + Expect(err).To(MatchError(expectedErr)) + // the permission was resolved and its removal was attempted + gatewayClient.AssertCalled(GinkgoT(), removeMethod, mock.Anything, mock.Anything) + + graphErr, ok := errorcode.ToError(expectedErr) + Expect(ok).To(BeTrue()) + entries := logEntries(logBuf) + // the failure is logged with its error code and error text, whatever its level + Expect(entries).To(ContainElement(SatisfyAll( + HaveKeyWithValue("level", level), + HaveKeyWithValue("itemID", storagespace.FormatResourceID(getShareResponse.Share.ResourceId)), + HaveKeyWithValue("permissionID", "permissionid"), + HaveKeyWithValue("errorCode", graphErr.GetCode().String()), + HaveKeyWithValue("error", expectedErr.Error()), + ))) + errorEntries := entriesAtLevel(entries, "error") + if level == "error" { + Expect(errorEntries).To(HaveLen(1)) + } else { + Expect(entries).ToNot(ContainElement(HaveKeyWithValue("level", BeElementOf("error", "warn")))) + } + for _, payloadKey := range []string{"share", "res", "response", "request", "Body", "body"} { + Expect(entries).ToNot(ContainElement(HaveKey(payloadKey))) + } + }, + Entry("public link: internal error", + func() string { + // resolved as a public link on the item + getPublicShareResponse.Share = &link.PublicShare{ + Id: &link.PublicShareId{OpaqueId: "permissionid"}, + ResourceId: getShareResponse.Share.ResourceId, + } + gatewayClient.On("GetPublicShare", mock.Anything, mock.Anything).Return(&getPublicShareResponse, nil) + gatewayClient.On("RemovePublicShare", mock.Anything, mock.Anything).Return(&link.RemovePublicShareResponse{ + Status: status.NewInternal(context.Background(), "link manager unavailable"), + }, nil) + return "RemovePublicShare" + }, + errorcode.New(errorcode.GeneralException, "link manager unavailable").WithOrigin(errorcode.ErrorOriginCS3), "error"), + Entry("ocm share: internal error", + func() string { + // neither a public link nor a user share, but an ocm share on the item + cfg.IncludeOCMSharees = true + getPublicShareResponse.Status = status.NewNotFound(context.Background(), "") + gatewayClient.On("GetPublicShare", mock.Anything, mock.Anything).Return(&getPublicShareResponse, nil) + gatewayClient.On("GetShare", mock.Anything, mock.Anything).Return(&collaboration.GetShareResponse{ + Status: status.NewNotFound(context.Background(), ""), + }, nil) + gatewayClient.On("GetOCMShare", mock.Anything, mock.Anything).Return(&ocm.GetOCMShareResponse{ + Status: status.NewOK(context.Background()), + Share: &ocm.Share{ + Id: &ocm.ShareId{OpaqueId: "permissionid"}, + ResourceId: getShareResponse.Share.ResourceId, + }, + }, nil) + gatewayClient.On("RemoveOCMShare", mock.Anything, mock.Anything).Return(&ocm.RemoveOCMShareResponse{ + Status: status.NewInternal(context.Background(), "ocm share manager unavailable"), + }, nil) + return "RemoveOCMShare" + }, + errorcode.New(errorcode.GeneralException, "ocm share manager unavailable").WithOrigin(errorcode.ErrorOriginCS3), "error"), + Entry("user share: already removed", + func() string { + // resolved as a user share, which is gone by the time it is removed + getPublicShareResponse.Status = status.NewNotFound(context.Background(), "") + gatewayClient.On("GetPublicShare", mock.Anything, mock.Anything).Return(&getPublicShareResponse, nil) + gatewayClient.On("GetShare", mock.Anything, mock.Anything).Return(&getShareResponse, nil) + gatewayClient.On("RemoveShare", mock.Anything, mock.Anything).Return(&collaboration.RemoveShareResponse{ + Status: status.NewNotFound(context.Background(), "share already removed"), + }, nil) + return "RemoveShare" + }, + errorcode.New(errorcode.ItemNotFound, "share already removed").WithOrigin(errorcode.ErrorOriginCS3), "debug"), + ) + It("logs and traces a share lookup failure hidden by the ocm fallback once as error", func() { + var logBuf bytes.Buffer + sr, tp := newSpanRecorder() + cfg.IncludeOCMSharees = true + service, err := svc.NewDriveItemPermissionsService(log.Logger{Logger: zerolog.New(&logBuf)}, gatewaySelector, cache, cfg, tp) + Expect(err).ToNot(HaveOccurred()) + + // the user share lookup fails in the share manager, the ocm fallback does not know the permission + getPublicShareResponse.Status = status.NewNotFound(context.Background(), "") + gatewayClient.On("GetPublicShare", mock.Anything, mock.Anything).Return(&getPublicShareResponse, nil) + gatewayClient.On("GetShare", mock.Anything, mock.Anything).Return(&collaboration.GetShareResponse{ + Status: status.NewInternal(context.Background(), "lookup failed for /Users/alice/Private/salary-2026.ods"), + }, nil) + gatewayClient.On("GetOCMShare", mock.Anything, mock.Anything).Return(&ocm.GetOCMShareResponse{ + Status: status.NewNotFound(context.Background(), "not found"), + }, nil) + + err = service.DeletePermission(ctx, getShareResponse.Share.ResourceId, "permissionid") + // the ocm fallback result is still returned + Expect(err).To(MatchError(errorcode.New(errorcode.ItemNotFound, "not found").WithOrigin(errorcode.ErrorOriginCS3))) + gatewayClient.AssertCalled(GinkgoT(), "GetOCMShare", mock.Anything, mock.Anything) + + entries := logEntries(&logBuf) + errorEntries := entriesAtLevel(entries, "error") + Expect(errorEntries).To(HaveLen(1)) + Expect(errorEntries[0]).To(SatisfyAll( + HaveKeyWithValue("message", "could not resolve permission"), + HaveKeyWithValue("itemID", storagespace.FormatResourceID(getShareResponse.Share.ResourceId)), + HaveKeyWithValue("permissionID", "permissionid"), + HaveKeyWithValue("errorCode", "itemNotFound"), + HaveKeyWithValue("lookupErrorCode", "generalException"), + // the texts of both the hidden infrastructure failure and the returned not found are logged + HaveKeyWithValue("lookupError", errorcode.New(errorcode.GeneralException, "lookup failed for /Users/alice/Private/salary-2026.ods").WithOrigin(errorcode.ErrorOriginCS3).Error()), + HaveKeyWithValue("error", err.Error()), + )) + + // the span reports the hidden infrastructure failure by its code only + span := endedSpan(sr, "DeletePermission", "salary-2026.ods", "lookup failed") + Expect(span.Status().Code).To(Equal(codes.Error)) + Expect(span.Status().Description).To(Equal("generalException")) + Expect(span.Attributes()).To(ContainElement(attribute.String("error.type", "itemNotFound"))) + }) + It("does not mark the span when no share lookup finds the permission", func() { + sr, tp := newSpanRecorder() + cfg.IncludeOCMSharees = true + service, err := svc.NewDriveItemPermissionsService(log.NewLogger(), gatewaySelector, cache, cfg, tp) + Expect(err).ToNot(HaveOccurred()) + + getPublicShareResponse.Status = status.NewNotFound(context.Background(), "") + gatewayClient.On("GetPublicShare", mock.Anything, mock.Anything).Return(&getPublicShareResponse, nil) + gatewayClient.On("GetShare", mock.Anything, mock.Anything).Return(&collaboration.GetShareResponse{ + Status: status.NewNotFound(context.Background(), "not found"), + }, nil) + gatewayClient.On("GetOCMShare", mock.Anything, mock.Anything).Return(&ocm.GetOCMShareResponse{ + Status: status.NewNotFound(context.Background(), "not found"), + }, nil) + + err = service.DeletePermission(ctx, getShareResponse.Share.ResourceId, "permissionid") + Expect(err).To(MatchError(errorcode.New(errorcode.ItemNotFound, "not found").WithOrigin(errorcode.ErrorOriginCS3))) + + span := endedSpan(sr, "DeletePermission") + Expect(span.Status().Code).To(Equal(codes.Unset)) + Expect(span.Attributes()).To(ContainElement(attribute.String("error.type", "itemNotFound"))) + }) + It("does not mark the span of a permission that is not found without the ocm fallback", func() { + sr, tp := newSpanRecorder() + service, err := svc.NewDriveItemPermissionsService(log.NewLogger(), gatewaySelector, cache, cfg, tp) + Expect(err).ToNot(HaveOccurred()) + + getPublicShareResponse.Status = status.NewNotFound(context.Background(), "") + gatewayClient.On("GetPublicShare", mock.Anything, mock.Anything).Return(&getPublicShareResponse, nil) + gatewayClient.On("GetShare", mock.Anything, mock.Anything).Return(&collaboration.GetShareResponse{ + Status: status.NewNotFound(context.Background(), "not found"), + }, nil) + + err = service.DeletePermission(ctx, getShareResponse.Share.ResourceId, "permissionid") + Expect(err).To(MatchError(errorcode.New(errorcode.ItemNotFound, "not found").WithOrigin(errorcode.ErrorOriginCS3))) + gatewayClient.AssertNotCalled(GinkgoT(), "GetOCMShare", mock.Anything, mock.Anything) + + span := endedSpan(sr, "DeletePermission") + Expect(span.Status().Code).To(Equal(codes.Unset)) + Expect(span.Attributes()).To(ContainElement(attribute.String("error.type", "itemNotFound"))) + }) + It("does not mark the span when the ocm fallback succeeds after a share lookup failure", func() { + sr, tp := newSpanRecorder() + cfg.IncludeOCMSharees = true + service, err := svc.NewDriveItemPermissionsService(log.NewLogger(), gatewaySelector, cache, cfg, tp) + Expect(err).ToNot(HaveOccurred()) + + getPublicShareResponse.Status = status.NewNotFound(context.Background(), "") + gatewayClient.On("GetPublicShare", mock.Anything, mock.Anything).Return(&getPublicShareResponse, nil) + gatewayClient.On("GetShare", mock.Anything, mock.Anything).Return(&collaboration.GetShareResponse{ + Status: status.NewInternal(context.Background(), "share manager unavailable"), + }, nil) + gatewayClient.On("GetOCMShare", mock.Anything, mock.Anything).Return(&ocm.GetOCMShareResponse{ + Status: status.NewOK(context.Background()), + Share: &ocm.Share{ + Id: &ocm.ShareId{OpaqueId: "permissionid"}, + ResourceId: getShareResponse.Share.ResourceId, + }, + }, nil) + gatewayClient.On("RemoveOCMShare", mock.Anything, mock.Anything).Return(&ocm.RemoveOCMShareResponse{ + Status: status.NewOK(context.Background()), + }, nil) + + Expect(service.DeletePermission(ctx, getShareResponse.Share.ResourceId, "permissionid")).To(Succeed()) + gatewayClient.AssertCalled(GinkgoT(), "RemoveOCMShare", mock.Anything, mock.Anything) + + span := endedSpan(sr, "DeletePermission") + Expect(span.Status().Code).To(Equal(codes.Unset)) + Expect(span.Attributes()).ToNot(ContainElement(HaveField("Key", attribute.Key("error.type")))) + }) + It("logs a permission without a resolvable resource id as debug with the item and permission ids", func() { + service, logBuf := newLoggedService() + + // a public link without a resource id + gatewayClient.On("GetPublicShare", mock.Anything, mock.Anything).Return(&getPublicShareResponse, nil) + + err := service.DeletePermission(ctx, getShareResponse.Share.ResourceId, "permissionid") + Expect(err).To(MatchError(errorcode.New(errorcode.ItemNotFound, "failed to resolve resource id for shared resource"))) + + entries := logEntries(logBuf) + Expect(entries).To(ContainElement(SatisfyAll( + HaveKeyWithValue("level", "debug"), + HaveKeyWithValue("message", "could not resolve the shared resource of the permission"), + HaveKeyWithValue("itemID", storagespace.FormatResourceID(getShareResponse.Share.ResourceId)), + HaveKeyWithValue("permissionID", "permissionid"), + ))) + Expect(entries).ToNot(ContainElement(HaveKeyWithValue("level", BeElementOf("error", "warn")))) + }) + It("does not log the not found results of permission type probing as errors", func() { + service, logBuf := newLoggedService() + + // not a public link, but a user share + getPublicShareResponse.Status = status.NewNotFound(context.Background(), "") + gatewayClient.On("GetPublicShare", mock.Anything, mock.Anything).Return(&getPublicShareResponse, nil) + gatewayClient.On("GetShare", mock.Anything, mock.Anything).Return(&getShareResponse, nil) + gatewayClient.On("RemoveShare", mock.Anything, mock.Anything).Return(&collaboration.RemoveShareResponse{Status: status.NewOK(ctx)}, nil) + + err := service.DeletePermission(ctx, getShareResponse.Share.ResourceId, "permissionid") + Expect(err).ToNot(HaveOccurred()) + gatewayClient.AssertCalled(GinkgoT(), "RemoveShare", mock.Anything, mock.Anything) + + Expect(logEntries(logBuf)).ToNot(ContainElement(HaveKeyWithValue("level", BeElementOf("error", "warn")))) + }) It("deletes a space permission as expected", func() { getPublicShareResponse.Status = status.NewNotFound(context.Background(), "") gatewayClient.On("GetPublicShare", mock.Anything, mock.Anything).Return(&getPublicShareResponse, nil) @@ -885,6 +2527,72 @@ var _ = Describe("DriveItemPermissionsService", func() { Expect(err).To(MatchError(errorcode.New(errorcode.InvalidRequest, "permissionID and itemID do not match"))) }) + It("logs a permission and item id mismatch as debug with the item and permission ids", func() { + service, logBuf := newLoggedService() + + // not a public link, but a user share on another resource than the one in the request + getPublicShareResponse.Status = status.NewNotFound(context.Background(), "") + gatewayClient.On("GetPublicShare", mock.Anything, mock.Anything).Return(&getPublicShareResponse, nil) + getShareResponse.Share.ResourceId = &provider.ResourceId{StorageId: "3", SpaceId: "4", OpaqueId: "5"} + gatewayClient.On("GetShare", mock.Anything, mock.Anything).Return(&getShareResponse, nil) + + itemID := &provider.ResourceId{StorageId: "1", SpaceId: "2", OpaqueId: "3"} + err := service.DeletePermission(ctx, itemID, "permissionid") + Expect(err).To(MatchError(errorcode.New(errorcode.InvalidRequest, "permissionID and itemID do not match"))) + // nothing is removed after the mismatch + for _, method := range []string{"RemoveShare", "RemovePublicShare", "RemoveOCMShare"} { + gatewayClient.AssertNotCalled(GinkgoT(), method, mock.Anything, mock.Anything) + } + + entries := logEntries(logBuf) + var mismatchEntries []map[string]any + for _, entry := range entries { + if entry["level"] == "debug" && entry["itemID"] == storagespace.FormatResourceID(itemID) && entry["permissionID"] == "permissionid" { + mismatchEntries = append(mismatchEntries, entry) + } + } + Expect(mismatchEntries).To(HaveLen(1)) + Expect(entries).ToNot(ContainElement(HaveKeyWithValue("level", BeElementOf("error", "warn")))) + }) + }) + Describe("DeleteSpaceRootPermission", func() { + It("records a DeleteSpaceRootPermission span as the parent of the DeletePermission span", func() { + sr, tp := newSpanRecorder() + service, err := svc.NewDriveItemPermissionsService(log.NewLogger(), gatewaySelector, cache, cfg, tp) + Expect(err).ToNot(HaveOccurred()) + + spaceRoot := &provider.ResourceId{StorageId: "1", SpaceId: "2", OpaqueId: "2"} + gatewayClient.On("ListStorageSpaces", mock.Anything, mock.Anything).Return(&provider.ListStorageSpacesResponse{ + Status: status.NewOK(ctx), + StorageSpaces: []*provider.StorageSpace{ + {Id: &provider.StorageSpaceId{OpaqueId: "2"}, SpaceType: "project", Root: spaceRoot}, + }, + }, nil) + gatewayClient.On("GetPublicShare", mock.Anything, mock.Anything).Return(&link.GetPublicShareResponse{ + Status: status.NewNotFound(ctx, ""), + }, nil) + gatewayClient.On("RemoveShare", mock.Anything, mock.Anything).Return(&collaboration.RemoveShareResponse{Status: status.NewOK(ctx)}, nil) + + err = service.DeleteSpaceRootPermission(context.Background(), &provider.ResourceId{StorageId: "1", SpaceId: "2"}, "shareid") + Expect(err).ToNot(HaveOccurred()) + // the space was resolved and DeletePermission removed the space permission + gatewayClient.AssertCalled(GinkgoT(), "RemoveShare", mock.Anything, mock.MatchedBy(func(req *collaboration.RemoveShareRequest) bool { + return req.GetRef().GetId().GetOpaqueId() == "shareid" + })) + + spans := map[string]sdktrace.ReadOnlySpan{} + for _, s := range sr.Ended() { + spans[s.Name()] = s + } + Expect(spans).To(HaveKey("DeleteSpaceRootPermission")) + Expect(spans).To(HaveKey("DeletePermission")) + parent := spans["DeleteSpaceRootPermission"].SpanContext() + child := spans["DeletePermission"] + Expect(parent.IsValid()).To(BeTrue()) + Expect(child.SpanContext().IsValid()).To(BeTrue()) + Expect(child.Parent().SpanID()).To(Equal(parent.SpanID())) + Expect(child.SpanContext().TraceID()).To(Equal(parent.TraceID())) + }) }) Describe("UpdatePermission", func() { var ( @@ -994,6 +2702,418 @@ var _ = Describe("DriveItemPermissionsService", func() { Expect(err).To(HaveOccurred()) Expect(res).To(BeZero()) }) + It("logs a gateway selection failure while listing space root shares as error in the helper and the operation with the item and permission ids", func() { + gatewayErr := errors.New("no gateway available") + spaceRootID := &provider.ResourceId{StorageId: "1", SpaceId: "2", OpaqueId: "2"} + // getPermissionByID and the public link lookup get a client, the space root share listing does not + gatewaySelector.EXPECT().Next().Unset() + gatewaySelector.EXPECT().Next().Return(gatewayClient, nil).Times(2) + gatewaySelector.EXPECT().Next().Return(nil, gatewayErr).Times(1) + service, logBuf := newLoggedService() + getPublicShareMockResponse.Share = nil + getPublicShareMockResponse.Status = status.NewNotFound(ctx, "not found") + gatewayClient.On("GetPublicShare", mock.Anything, mock.Anything).Return(getPublicShareMockResponse, nil) + + _, err := service.UpdatePermission(ctx, spaceRootID, "permissionid", driveItemPermission) + Expect(err).To(MatchError(errorcode.New(errorcode.GeneralException, gatewayErr.Error()))) + // the lookup stops at the failed space root share listing, nothing is updated + for _, method := range []string{"ListShares", "UpdateShare", "UpdatePublicShare", "Stat"} { + gatewayClient.AssertNotCalled(GinkgoT(), method, mock.Anything, mock.Anything) + } + + entries := logEntries(logBuf) + // the helper and the operation both log the reason, the operation with the item and permission ids + Expect(entriesAtLevel(entries, "error")).To(ConsistOf( + gatewayHelperEntry("could not select next gateway client", gatewayErr.Error()), + SatisfyAll( + HaveKeyWithValue("itemID", storagespace.FormatResourceID(spaceRootID)), + HaveKeyWithValue("permissionID", "permissionid"), + HaveKeyWithValue("error", err.Error()), + ), + )) + for _, payloadKey := range []string{"share", "shares", "res", "response", "request", "Body", "body"} { + Expect(entries).ToNot(ContainElement(HaveKey(payloadKey))) + } + }) + It("logs the identity backend error when resolving a user share grantee fails", func() { + service, logBuf := newLoggedService() + + const identityBackendMessage = "ldap search failed for cn=private-group-dn-42,ou=groups" + getPublicShareMockResponse.Share = nil + getPublicShareMockResponse.Status = status.NewNotFound(ctx, "not found") + gatewayClient.On("GetPublicShare", mock.Anything, mock.Anything).Return(getPublicShareMockResponse, nil) + getShareMockResponse.Share.Grantee = &provider.Grantee{ + Type: provider.GranteeType_GRANTEE_TYPE_GROUP, + Id: &provider.Grantee_GroupId{GroupId: &grouppb.GroupId{OpaqueId: "groupid"}}, + } + gatewayClient.On("GetShare", mock.Anything, mock.Anything).Return(getShareMockResponse, nil) + gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(statResponse, nil) + gatewayClient.On("GetGroup", mock.Anything, mock.Anything).Return(&grouppb.GetGroupResponse{ + Status: status.NewInternal(context.Background(), identityBackendMessage), + }, nil) + + _, err := service.UpdatePermission(ctx, driveItemId, "permissionid", driveItemPermission) + // the returned error is unchanged: the share conversion error + Expect(err).To(MatchError(errorcode.New(errorcode.GeneralException, + errorcode.New(errorcode.GeneralException, identityBackendMessage).Error()))) + // the user share grantee was looked up, nothing is updated + gatewayClient.AssertCalled(GinkgoT(), "GetGroup", mock.Anything, mock.MatchedBy(func(req *grouppb.GetGroupRequest) bool { + return req.GetGroupId().GetOpaqueId() == "groupid" + })) + for _, method := range []string{"UpdateShare", "UpdatePublicShare"} { + gatewayClient.AssertNotCalled(GinkgoT(), method, mock.Anything, mock.Anything) + } + + entries := logEntries(logBuf) + errorEntries := entriesAtLevel(entries, "error") + Expect(errorEntries).To(HaveLen(1)) + Expect(errorEntries[0]).To(SatisfyAll( + HaveKeyWithValue("itemID", storagespace.FormatResourceID(driveItemId)), + HaveKeyWithValue("permissionID", "permissionid"), + HaveKeyWithValue("error", err.Error()), + )) + for _, payloadKey := range []string{"share", "shares", "group", "res", "response", "request", "Body", "body"} { + Expect(entries).ToNot(ContainElement(HaveKey(payloadKey))) + } + }) + DescribeTable("logs public link update failures as error with the item and permission ids", + func(setup func(), expectedErr error, helperEntries int) { + setup() + service, logBuf := newLoggedService() + + sharingLink := libregraph.NewSharingLink() + sharingLink.SetLibreGraphDisplayName(TestLinkName) + driveItemPermission.SetLink(*sharingLink) + _, err := service.UpdatePermission(ctx, driveItemId, "permissionid", driveItemPermission) + Expect(err).To(MatchError(expectedErr)) + // the permission was resolved as a public link, user and ocm shares are not touched + gatewayClient.AssertCalled(GinkgoT(), "GetPublicShare", mock.Anything, mock.Anything) + for _, method := range []string{"GetShare", "UpdateShare", "GetOCMShare"} { + gatewayClient.AssertNotCalled(GinkgoT(), method, mock.Anything, mock.Anything) + } + + entries := logEntries(logBuf) + // the operation's entry carries the ids, a helper that cannot select a gateway logs the reason + var operationEntries, helpers []map[string]any + for _, entry := range entriesAtLevel(entries, "error") { + if _, ok := entry["itemID"]; ok { + operationEntries = append(operationEntries, entry) + } else { + helpers = append(helpers, entry) + } + } + Expect(operationEntries).To(HaveLen(1)) + Expect(operationEntries[0]).To(SatisfyAll( + HaveKeyWithValue("itemID", storagespace.FormatResourceID(driveItemId)), + HaveKeyWithValue("permissionID", "permissionid"), + HaveKeyWithValue("error", expectedErr.Error()), + )) + Expect(helpers).To(HaveLen(helperEntries)) + for _, entry := range helpers { + Expect(entry).To(gatewayHelperEntry("could not select next gateway client", "no gateway available")) + } + for _, payloadKey := range []string{"share", "link", "Link", "res", "response", "request", "Body", "body", "password"} { + Expect(entries).ToNot(ContainElement(HaveKey(payloadKey))) + } + // the public link token must never be logged + raw, err := json.Marshal(entries) + Expect(err).ToNot(HaveOccurred()) + Expect(string(raw)).ToNot(ContainSubstring(`"token"`)) + }, + Entry("UpdatePublicShare returns an internal error", + func() { + gatewayClient.On("GetPublicShare", mock.Anything, mock.Anything).Return(getPublicShareMockResponse, nil) + gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(statResponse, nil) + gatewayClient.On("UpdatePublicShare", mock.Anything, mock.Anything).Return(&link.UpdatePublicShareResponse{ + Status: status.NewInternal(ctx, "link manager unavailable"), + }, nil) + }, + errorcode.New(errorcode.GeneralException, "link manager unavailable").WithOrigin(errorcode.ErrorOriginCS3), 0), + Entry("gateway selection fails in the public link update", + func() { + // getPermissionByID and the public link lookup get a client, the link update does not + gatewaySelector.EXPECT().Next().Unset() + gatewaySelector.EXPECT().Next().Return(gatewayClient, nil).Times(2) + gatewaySelector.EXPECT().Next().Return(nil, errors.New("no gateway available")).Times(1) + gatewayClient.On("GetPublicShare", mock.Anything, mock.Anything).Return(getPublicShareMockResponse, nil) + }, + errorcode.New(errorcode.GeneralException, "no gateway available"), 1), + ) + It("logs a missing public link item at debug level with the backend stat message", func() { + service, logBuf := newLoggedService() + + // the permission resolves to a public link, but its item can no longer be stat'ed; + // decomposedfs reports a missing node as "/" + statMessage := "stat: 7c3e9a1b-parent/private-financial-report-2026.xlsx" + gatewayClient.On("GetPublicShare", mock.Anything, mock.Anything).Return(getPublicShareMockResponse, nil) + gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(&provider.StatResponse{ + Status: status.NewNotFound(ctx, statMessage), + }, nil) + + sharingLink := libregraph.NewSharingLink() + sharingLink.SetLibreGraphDisplayName(TestLinkName) + driveItemPermission.SetLink(*sharingLink) + _, err := service.UpdatePermission(ctx, driveItemId, "permissionid", driveItemPermission) + Expect(err).To(MatchError(errorcode.New(errorcode.ItemNotFound, statMessage).WithOrigin(errorcode.ErrorOriginCS3))) + gatewayClient.AssertCalled(GinkgoT(), "Stat", mock.Anything, mock.Anything) + // nothing is updated after the failed stat + for _, method := range []string{"UpdatePublicShare", "UpdateShare", "UpdateOCMShare"} { + gatewayClient.AssertNotCalled(GinkgoT(), method, mock.Anything, mock.Anything) + } + + entries := logEntries(logBuf) + var debugEntries []map[string]any + for _, entry := range entries { + if entry["level"] == "debug" && entry["itemID"] == storagespace.FormatResourceID(driveItemId) && entry["permissionID"] == "permissionid" { + debugEntries = append(debugEntries, entry) + } + } + Expect(debugEntries).To(HaveLen(1)) + // the debug entry carries the backend message, so the missing item can be identified + Expect(debugEntries[0]).To(HaveKeyWithValue("error", ContainSubstring(statMessage))) + Expect(entries).ToNot(ContainElement(HaveKeyWithValue("level", BeElementOf("error", "warn")))) + }) + It("logs a user share update failure once as error with the item and permission ids", func() { + service, logBuf := newLoggedService() + + // resolved as a user share on the item, whose update fails + gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(statResponse, nil) + gatewayClient.On("GetUser", mock.Anything, mock.Anything).Return(getUserResponse, nil) + getPublicShareMockResponse.Share = nil + getPublicShareMockResponse.Status = status.NewNotFound(ctx, "not found") + gatewayClient.On("GetPublicShare", mock.Anything, mock.Anything).Return(getPublicShareMockResponse, nil) + gatewayClient.On("GetShare", mock.Anything, mock.Anything).Return(getShareMockResponse, nil) + gatewayClient.On("UpdateShare", mock.Anything, mock.Anything).Return(&collaboration.UpdateShareResponse{ + Status: status.NewInternal(ctx, "share manager unavailable"), + }, nil) + + driveItemPermission.SetExpirationDateTime(time.Now().Add(time.Hour)) + _, err := service.UpdatePermission(ctx, driveItemId, "permissionid", driveItemPermission) + Expect(err).To(MatchError(errorcode.New(errorcode.GeneralException, "share manager unavailable").WithOrigin(errorcode.ErrorOriginCS3))) + gatewayClient.AssertCalled(GinkgoT(), "UpdateShare", mock.Anything, mock.Anything) + + entries := logEntries(logBuf) + errorEntries := entriesAtLevel(entries, "error") + Expect(errorEntries).To(HaveLen(1)) + Expect(errorEntries[0]).To(SatisfyAll( + HaveKeyWithValue("itemID", storagespace.FormatResourceID(driveItemId)), + HaveKeyWithValue("permissionID", "permissionid"), + HaveKeyWithValue("errorCode", "generalException"), + HaveKeyWithValue("error", err.Error()), + )) + for _, payloadKey := range []string{"share", "shares", "res", "response", "request", "Body", "body"} { + Expect(entries).ToNot(ContainElement(HaveKey(payloadKey))) + } + }) + It("logs and traces a failed ocm share update once with the cause of both update attempts", func() { + var logBuf bytes.Buffer + sr, tp := newSpanRecorder() + cfg.IncludeOCMSharees = true + service, err := svc.NewDriveItemPermissionsService(log.Logger{Logger: zerolog.New(&logBuf)}, gatewaySelector, cache, cfg, tp) + Expect(err).ToNot(HaveOccurred()) + + // the permission is neither a public link nor a user share, but an ocm share + getPublicShareMockResponse.Share = nil + getPublicShareMockResponse.Status = status.NewNotFound(ctx, "not found") + gatewayClient.On("GetPublicShare", mock.Anything, mock.Anything).Return(getPublicShareMockResponse, nil) + getShareMockResponse.Share = nil + getShareMockResponse.Status = status.NewNotFound(ctx, "not found") + gatewayClient.On("GetShare", mock.Anything, mock.Anything).Return(getShareMockResponse, nil) + gatewayClient.On("GetOCMShare", mock.Anything, mock.Anything).Return(&ocm.GetOCMShareResponse{ + Status: status.NewOK(ctx), + Share: &ocm.Share{Id: &ocm.ShareId{OpaqueId: "permissionid"}, ResourceId: driveItemId}, + }, nil) + gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(statResponse, nil) + // the user share update attempt does not find the share, the ocm share update fails + gatewayClient.On("UpdateShare", mock.Anything, mock.Anything).Return(&collaboration.UpdateShareResponse{ + Status: status.NewNotFound(ctx, "not found"), + }, nil) + gatewayClient.On("UpdateOCMShare", mock.Anything, mock.Anything).Return(&ocm.UpdateOCMShareResponse{ + Status: status.NewInternal(ctx, "ocm share manager unavailable"), + }, nil) + + driveItemPermission.SetExpirationDateTime(time.Now().Add(time.Hour)) + _, err = service.UpdatePermission(ctx, driveItemId, "permissionid", driveItemPermission) + // the returned error is unchanged: the error of the user share update attempt + Expect(err).To(MatchError(errorcode.New(errorcode.ItemNotFound, "not found").WithOrigin(errorcode.ErrorOriginCS3))) + gatewayClient.AssertCalled(GinkgoT(), "UpdateOCMShare", mock.Anything, mock.Anything) + + entries := logEntries(&logBuf) + errorEntries := entriesAtLevel(entries, "error") + Expect(errorEntries).To(HaveLen(1)) + Expect(errorEntries[0]).To(SatisfyAll( + HaveKeyWithValue("message", "could not update permission"), + HaveKeyWithValue("itemID", storagespace.FormatResourceID(driveItemId)), + HaveKeyWithValue("permissionID", "permissionid"), + HaveKeyWithValue("errorCode", "itemNotFound"), + HaveKeyWithValue("ocmErrorCode", "generalException"), + // the texts of both the failed ocm update and the returned not found are logged + HaveKeyWithValue("ocmError", errorcode.New(errorcode.GeneralException, "ocm share manager unavailable").WithOrigin(errorcode.ErrorOriginCS3).Error()), + HaveKeyWithValue("error", err.Error()), + )) + + // the span reports the failed ocm update by its code only + span := endedSpan(sr, "UpdatePermission", "ocm share manager unavailable") + Expect(span.Status().Code).To(Equal(codes.Error)) + Expect(span.Status().Description).To(Equal("generalException")) + Expect(span.Attributes()).To(ContainElement(attribute.String("error.type", "itemNotFound"))) + }) + It("does not mark the span when neither update attempt finds the share", func() { + sr, tp := newSpanRecorder() + cfg.IncludeOCMSharees = true + service, err := svc.NewDriveItemPermissionsService(log.NewLogger(), gatewaySelector, cache, cfg, tp) + Expect(err).ToNot(HaveOccurred()) + + getPublicShareMockResponse.Share = nil + getPublicShareMockResponse.Status = status.NewNotFound(ctx, "not found") + gatewayClient.On("GetPublicShare", mock.Anything, mock.Anything).Return(getPublicShareMockResponse, nil) + getShareMockResponse.Share = nil + getShareMockResponse.Status = status.NewNotFound(ctx, "not found") + gatewayClient.On("GetShare", mock.Anything, mock.Anything).Return(getShareMockResponse, nil) + gatewayClient.On("GetOCMShare", mock.Anything, mock.Anything).Return(&ocm.GetOCMShareResponse{ + Status: status.NewOK(ctx), + Share: &ocm.Share{Id: &ocm.ShareId{OpaqueId: "permissionid"}, ResourceId: driveItemId}, + }, nil) + gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(statResponse, nil) + gatewayClient.On("UpdateShare", mock.Anything, mock.Anything).Return(&collaboration.UpdateShareResponse{ + Status: status.NewNotFound(ctx, "not found"), + }, nil) + gatewayClient.On("UpdateOCMShare", mock.Anything, mock.Anything).Return(&ocm.UpdateOCMShareResponse{ + Status: status.NewNotFound(ctx, "not found"), + }, nil) + + driveItemPermission.SetExpirationDateTime(time.Now().Add(time.Hour)) + _, err = service.UpdatePermission(ctx, driveItemId, "permissionid", driveItemPermission) + Expect(err).To(MatchError(errorcode.New(errorcode.ItemNotFound, "not found").WithOrigin(errorcode.ErrorOriginCS3))) + gatewayClient.AssertCalled(GinkgoT(), "UpdateOCMShare", mock.Anything, mock.Anything) + + span := endedSpan(sr, "UpdatePermission") + Expect(span.Status().Code).To(Equal(codes.Unset)) + Expect(span.Attributes()).To(ContainElement(attribute.String("error.type", "itemNotFound"))) + }) + It("logs the identity backend error when converting the updated user share fails", func() { + service, logBuf := newLoggedService() + + // resolved as a user share on the item, the updated share is returned with a + // group grantee that has not been looked up (and cached) before + const identityBackendMessage = "ldap search failed for cn=private-group-dn-42,ou=groups" + gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(statResponse, nil) + gatewayClient.On("GetUser", mock.Anything, mock.Anything).Return(getUserResponse, nil) + getPublicShareMockResponse.Share = nil + getPublicShareMockResponse.Status = status.NewNotFound(ctx, "not found") + gatewayClient.On("GetPublicShare", mock.Anything, mock.Anything).Return(getPublicShareMockResponse, nil) + gatewayClient.On("GetShare", mock.Anything, mock.Anything).Return(getShareMockResponse, nil) + updateShareMockResponse.Share = &collaboration.Share{ + Id: &collaboration.ShareId{OpaqueId: "permissionid"}, + ResourceId: driveItemId, + Grantee: &provider.Grantee{ + Type: provider.GranteeType_GRANTEE_TYPE_GROUP, + Id: &provider.Grantee_GroupId{GroupId: &grouppb.GroupId{OpaqueId: "groupid"}}, + }, + } + gatewayClient.On("UpdateShare", mock.Anything, mock.Anything).Return(updateShareMockResponse, nil) + gatewayClient.On("GetGroup", mock.Anything, mock.Anything).Return(&grouppb.GetGroupResponse{ + Status: status.NewInternal(ctx, identityBackendMessage), + }, nil) + + driveItemPermission.SetExpirationDateTime(time.Now().Add(time.Hour)) + _, err := service.UpdatePermission(ctx, driveItemId, "permissionid", driveItemPermission) + // the returned error is unchanged: the identity error wrapped by the share conversion + Expect(err).To(MatchError(errorcode.New(errorcode.GeneralException, + errorcode.New(errorcode.GeneralException, identityBackendMessage).Error()))) + gatewayClient.AssertCalled(GinkgoT(), "GetGroup", mock.Anything, mock.Anything) + + entries := logEntries(logBuf) + errorEntries := entriesAtLevel(entries, "error") + Expect(errorEntries).To(HaveLen(1)) + Expect(errorEntries[0]).To(SatisfyAll( + HaveKeyWithValue("itemID", storagespace.FormatResourceID(driveItemId)), + HaveKeyWithValue("permissionID", "permissionid"), + HaveKeyWithValue("errorCode", "generalException"), + HaveKeyWithValue("error", err.Error()), + )) + }) + It("does not log a permission that is not found by any lookup as error", func() { + service, logBuf := newLoggedService() + + getPublicShareMockResponse.Share = nil + getPublicShareMockResponse.Status = status.NewNotFound(ctx, "not found") + gatewayClient.On("GetPublicShare", mock.Anything, mock.Anything).Return(getPublicShareMockResponse, nil) + getShareMockResponse.Share = nil + getShareMockResponse.Status = status.NewNotFound(ctx, "not found") + gatewayClient.On("GetShare", mock.Anything, mock.Anything).Return(getShareMockResponse, nil) + + _, err := service.UpdatePermission(ctx, driveItemId, "permissionid", driveItemPermission) + Expect(errorcode.IsErrorCode(err, errorcode.ItemNotFound)).To(BeTrue()) + + Expect(logEntries(logBuf)).ToNot(ContainElement(HaveKeyWithValue("level", BeElementOf("error", "warn")))) + }) + It("logs and traces a share lookup failure hidden by the ocm fallback once as error", func() { + var logBuf bytes.Buffer + sr, tp := newSpanRecorder() + cfg.IncludeOCMSharees = true + service, err := svc.NewDriveItemPermissionsService(log.Logger{Logger: zerolog.New(&logBuf)}, gatewaySelector, cache, cfg, tp) + Expect(err).ToNot(HaveOccurred()) + + // the user share lookup fails in the share manager, the ocm fallback does not know the permission + getPublicShareMockResponse.Share = nil + getPublicShareMockResponse.Status = status.NewNotFound(ctx, "not found") + gatewayClient.On("GetPublicShare", mock.Anything, mock.Anything).Return(getPublicShareMockResponse, nil) + getShareMockResponse.Share = nil + getShareMockResponse.Status = status.NewInternal(ctx, "lookup failed for /Users/alice/Private/salary-2026.ods") + gatewayClient.On("GetShare", mock.Anything, mock.Anything).Return(getShareMockResponse, nil) + gatewayClient.On("GetOCMShare", mock.Anything, mock.Anything).Return(&ocm.GetOCMShareResponse{ + Status: status.NewNotFound(ctx, "not found"), + }, nil) + + _, err = service.UpdatePermission(ctx, driveItemId, "permissionid", driveItemPermission) + // the ocm fallback result is still returned + Expect(err).To(MatchError(errorcode.New(errorcode.ItemNotFound, "not found").WithOrigin(errorcode.ErrorOriginCS3))) + gatewayClient.AssertCalled(GinkgoT(), "GetOCMShare", mock.Anything, mock.Anything) + + entries := logEntries(&logBuf) + errorEntries := entriesAtLevel(entries, "error") + Expect(errorEntries).To(HaveLen(1)) + Expect(errorEntries[0]).To(SatisfyAll( + HaveKeyWithValue("message", "could not resolve permission"), + HaveKeyWithValue("itemID", storagespace.FormatResourceID(driveItemId)), + HaveKeyWithValue("permissionID", "permissionid"), + HaveKeyWithValue("errorCode", "itemNotFound"), + HaveKeyWithValue("lookupErrorCode", "generalException"), + // the texts of both the hidden infrastructure failure and the returned not found are logged + HaveKeyWithValue("lookupError", errorcode.New(errorcode.GeneralException, "lookup failed for /Users/alice/Private/salary-2026.ods").WithOrigin(errorcode.ErrorOriginCS3).Error()), + HaveKeyWithValue("error", err.Error()), + )) + + // the span reports the hidden infrastructure failure by its code only + span := endedSpan(sr, "UpdatePermission", "salary-2026.ods", "lookup failed") + Expect(span.Status().Code).To(Equal(codes.Error)) + Expect(span.Status().Description).To(Equal("generalException")) + Expect(span.Attributes()).To(ContainElement(attribute.String("error.type", "itemNotFound"))) + }) + It("does not mark the span when neither permission lookup finds the permission", func() { + sr, tp := newSpanRecorder() + cfg.IncludeOCMSharees = true + service, err := svc.NewDriveItemPermissionsService(log.NewLogger(), gatewaySelector, cache, cfg, tp) + Expect(err).ToNot(HaveOccurred()) + + getPublicShareMockResponse.Share = nil + getPublicShareMockResponse.Status = status.NewNotFound(ctx, "not found") + gatewayClient.On("GetPublicShare", mock.Anything, mock.Anything).Return(getPublicShareMockResponse, nil) + getShareMockResponse.Share = nil + getShareMockResponse.Status = status.NewNotFound(ctx, "not found") + gatewayClient.On("GetShare", mock.Anything, mock.Anything).Return(getShareMockResponse, nil) + gatewayClient.On("GetOCMShare", mock.Anything, mock.Anything).Return(&ocm.GetOCMShareResponse{ + Status: status.NewNotFound(ctx, "not found"), + }, nil) + + _, err = service.UpdatePermission(ctx, driveItemId, "permissionid", driveItemPermission) + Expect(err).To(MatchError(errorcode.New(errorcode.ItemNotFound, "not found").WithOrigin(errorcode.ErrorOriginCS3))) + + span := endedSpan(sr, "UpdatePermission") + Expect(span.Status().Code).To(Equal(codes.Unset)) + Expect(span.Attributes()).To(ContainElement(attribute.String("error.type", "itemNotFound"))) + }) It("fails to update permission when the resourceID mismatches with the shared resource's id", func() { getShareMockResponse.Share = nil getShareMockResponse.Status = status.NewNotFound(ctx, "not found") @@ -1011,6 +3131,31 @@ var _ = Describe("DriveItemPermissionsService", func() { Expect(err).To(MatchError(errorcode.New(errorcode.InvalidRequest, "permissionID and itemID do not match"))) Expect(res).To(BeZero()) }) + It("logs a permission and item id mismatch as debug with the item and permission ids", func() { + service, logBuf := newLoggedService() + + // the link belongs to another item than the one in the request + getPublicShareMockResponse.Share.ResourceId = &provider.ResourceId{StorageId: "1", SpaceId: "2", OpaqueId: "4"} + gatewayClient.On("GetPublicShare", mock.Anything, mock.Anything).Return(getPublicShareMockResponse, nil) + + driveItemPermission.SetExpirationDateTime(time.Now().Add(time.Hour)) + _, err := service.UpdatePermission(ctx, driveItemId, "permissionid", driveItemPermission) + Expect(err).To(MatchError(errorcode.New(errorcode.InvalidRequest, "permissionID and itemID do not match"))) + // nothing is updated after the mismatch + for _, method := range []string{"Stat", "UpdatePublicShare", "UpdateShare", "UpdateOCMShare"} { + gatewayClient.AssertNotCalled(GinkgoT(), method, mock.Anything, mock.Anything) + } + + entries := logEntries(logBuf) + var mismatchEntries []map[string]any + for _, entry := range entries { + if entry["level"] == "debug" && entry["itemID"] == storagespace.FormatResourceID(driveItemId) && entry["permissionID"] == "permissionid" { + mismatchEntries = append(mismatchEntries, entry) + } + } + Expect(mismatchEntries).To(HaveLen(1)) + Expect(entries).ToNot(ContainElement(HaveKeyWithValue("level", BeElementOf("error", "warn")))) + }) It("succeeds when trying to update a link permission with displayname", func() { gatewayClient.On("GetPublicShare", mock.Anything, mock.MatchedBy(func(req *link.GetPublicShareRequest) bool { return req.GetRef().GetId().GetOpaqueId() == "permissionid" @@ -1039,6 +3184,46 @@ var _ = Describe("DriveItemPermissionsService", func() { Expect(res.Link).ToNot(BeNil()) Expect(res.Link.GetLibreGraphDisplayName() == TestLinkName) }) + It("records an UpdateSpaceRootPermission span as the parent of the UpdatePermission span", func() { + sr, tp := newSpanRecorder() + service, err := svc.NewDriveItemPermissionsService(log.NewLogger(), gatewaySelector, cache, cfg, tp) + Expect(err).ToNot(HaveOccurred()) + + spaceRoot := &provider.ResourceId{StorageId: "1", SpaceId: "2", OpaqueId: "2"} + listSpacesResponse.StorageSpaces[0].SpaceType = "project" + listSpacesResponse.StorageSpaces[0].Root = spaceRoot + getPublicShareMockResponse.Share.ResourceId = spaceRoot + statResponse.Info.Id = spaceRoot + gatewayClient.On("ListStorageSpaces", mock.Anything, mock.Anything).Return(listSpacesResponse, nil) + gatewayClient.On("GetPublicShare", mock.Anything, mock.Anything).Return(getPublicShareMockResponse, nil) + gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(statResponse, nil) + gatewayClient.On("UpdatePublicShare", mock.Anything, mock.Anything).Return(updatePublicShareMockResponse, nil) + + sharingLink := libregraph.NewSharingLink() + sharingLink.SetLibreGraphDisplayName(TestLinkName) + driveItemPermission.SetLink(*sharingLink) + res, err := service.UpdateSpaceRootPermission(context.Background(), &provider.ResourceId{StorageId: "1", SpaceId: "2"}, "permissionid", driveItemPermission) + Expect(err).ToNot(HaveOccurred()) + // the space was resolved and UpdatePermission updated the link on the space root + Expect(res.Link).ToNot(BeNil()) + Expect(res.Link.GetLibreGraphDisplayName()).To(Equal(TestLinkName)) + gatewayClient.AssertCalled(GinkgoT(), "UpdatePublicShare", mock.Anything, mock.MatchedBy(func(req *link.UpdatePublicShareRequest) bool { + return req.GetRef().GetId().GetOpaqueId() == "permissionid" && req.GetUpdate().GetDisplayName() == TestLinkName + })) + + spans := map[string]sdktrace.ReadOnlySpan{} + for _, s := range sr.Ended() { + spans[s.Name()] = s + } + Expect(spans).To(HaveKey("UpdateSpaceRootPermission")) + Expect(spans).To(HaveKey("UpdatePermission")) + parent := spans["UpdateSpaceRootPermission"].SpanContext() + child := spans["UpdatePermission"] + Expect(parent.IsValid()).To(BeTrue()) + Expect(child.SpanContext().IsValid()).To(BeTrue()) + Expect(child.Parent().SpanID()).To(Equal(parent.SpanID())) + Expect(child.SpanContext().TraceID()).To(Equal(parent.TraceID())) + }) It("updates the expiration date", func() { gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(statResponse, nil) gatewayClient.On("GetUser", mock.Anything, mock.Anything).Return(getUserResponse, nil) @@ -1328,6 +3513,81 @@ var _ = Describe("DriveItemPermissionsApi", func() { } }) + DescribeTable("logs link password service failures by cause with the resource and permission ids", + func(spaceRoot bool, serviceErr error, expectedStatus int, level string) { + var logBuf bytes.Buffer + api, err := svc.NewDriveItemPermissionsApi(mockProvider, log.Logger{Logger: zerolog.New(&logBuf)}, defaults.FullDefaultConfig()) + Expect(err).ToNot(HaveOccurred()) + + rCTX.URLParams.Add("permissionID", "permissionid") + handler, method, ids := api.SetLinkPassword, "SetPublicLinkPassword", map[string]string{"itemID": "1$2!3"} + if spaceRoot { + handler, method, ids = api.SetSpaceRootLinkPassword, "SetPublicLinkPasswordOnSpaceRoot", map[string]string{"driveID": "1$2"} + } else { + rCTX.URLParams.Add("itemID", "1$2!3") + } + mockProvider.On(method, mock.Anything, mock.Anything, "permissionid", "s3cr3t-P4ss!"). + Return(libregraph.Permission{}, serviceErr).Once() + + responseRecorder := httptest.NewRecorder() + request := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(`{"password":"s3cr3t-P4ss!"}`)). + WithContext(context.WithValue(context.WithValue(context.Background(), chi.RouteCtxKey, rCTX), middleware.RequestIDKey, "request-42")) + request.Header.Set("Authorization", "Bearer secret-token-xyz") + handler(responseRecorder, request) + + // the HTTP response is the rendered service error, as before + Expect(responseRecorder.Code).To(Equal(expectedStatus)) + graphErr, ok := errorcode.ToError(serviceErr) + Expect(ok).To(BeTrue()) + jsonData := gjson.Get(responseRecorder.Body.String(), "error") + Expect(jsonData.Get("code").String()).To(Equal(graphErr.GetCode().String())) + Expect(jsonData.Get("message").String()).To(Equal(strings.TrimPrefix(serviceErr.Error(), graphErr.GetCode().String()+": "))) + // the service operation was attempted with the parsed ids and password + mockProvider.AssertExpectations(GinkgoT()) + + entries := logEntries(&logBuf) + var failureEntries []map[string]any + for _, entry := range entries { + matches := entry["level"] == level && entry["permissionID"] == "permissionid" + for k, v := range ids { + matches = matches && entry[k] == v + } + if matches { + failureEntries = append(failureEntries, entry) + } + } + Expect(failureEntries).To(HaveLen(1)) + // the failure is logged with its error code and error text, whatever its level + Expect(failureEntries[0]).To(SatisfyAll( + HaveKeyWithValue("request-id", "request-42"), + HaveKeyWithValue("errorCode", graphErr.GetCode().String()), + HaveKeyWithValue("error", serviceErr.Error()), + )) + if level == "error" { + Expect(entriesAtLevel(entries, "error")).To(HaveLen(1)) + } else { + Expect(entries).ToNot(ContainElement(HaveKeyWithValue("level", BeElementOf("error", "warn")))) + } + for _, payloadKey := range []string{"password", "Body", "body", "request", "response", "token", "Authorization"} { + Expect(entries).ToNot(ContainElement(HaveKey(payloadKey))) + } + // secrets are never logged: neither the password nor the bearer token + raw, err := json.Marshal(entries) + Expect(err).ToNot(HaveOccurred()) + for _, secret := range []string{"s3cr3t-P4ss!", "secret-token-xyz"} { + Expect(string(raw)).ToNot(ContainSubstring(secret)) + } + }, + Entry("SetLinkPassword: internal error", false, + errorcode.New(errorcode.GeneralException, "link manager unavailable"), http.StatusInternalServerError, "error"), + Entry("SetLinkPassword: link not found", false, + errorcode.New(errorcode.ItemNotFound, "link not found"), http.StatusNotFound, "debug"), + Entry("SetSpaceRootLinkPassword: internal error", true, + errorcode.New(errorcode.GeneralException, "link manager unavailable"), http.StatusInternalServerError, "error"), + Entry("SetSpaceRootLinkPassword: link not found", true, + errorcode.New(errorcode.ItemNotFound, "link not found"), http.StatusNotFound, "debug"), + ) + checkDriveIDAndItemIDValidation := func(handler http.HandlerFunc) { rCTX.URLParams.Add("itemID", "3$4!5") @@ -1494,6 +3754,175 @@ var _ = Describe("DriveItemPermissionsApi", func() { Expect(responseRecorder.Code).To(Equal(http.StatusBadRequest)) }) }) + + Describe("GetPermission", func() { + get := func() *httptest.ResponseRecorder { + responseRecorder := httptest.NewRecorder() + request := httptest.NewRequest(http.MethodGet, "/", nil). + WithContext(context.WithValue(context.Background(), chi.RouteCtxKey, rCTX)) + httpAPI.GetPermission(responseRecorder, request) + return responseRecorder + } + + It("passes the item and permission ID to the provider and renders the permission", func() { + rCTX.URLParams.Add("itemID", "1$2!3") + rCTX.URLParams.Add("permissionID", "perm%2Fid") + mockProvider.On("GetPermission", mock.Anything, mock.Anything, mock.Anything). + Return(func(ctx context.Context, itemID *provider.ResourceId, permissionID string) (libregraph.Permission, error) { + Expect(storagespace.FormatResourceID(itemID)).To(Equal("1$2!3")) + Expect(permissionID).To(Equal("perm/id")) + return libregraph.Permission{Id: libregraph.PtrString("perm/id")}, nil + }).Once() + + rr := get() + Expect(rr.Code).To(Equal(http.StatusOK)) + Expect(gjson.Get(rr.Body.String(), "id").String()).To(Equal("perm/id")) + }) + + It("rejects an itemID that does not belong to the drive", func() { + rCTX.URLParams.Add("itemID", "3$4!5") + rCTX.URLParams.Add("permissionID", "permid") + Expect(get().Code).To(Equal(http.StatusNotFound)) + }) + + It("rejects an empty permissionID", func() { + rCTX.URLParams.Add("itemID", "1$2!3") + Expect(get().Code).To(Equal(http.StatusBadRequest)) + }) + + It("renders a not found error of the provider", func() { + rCTX.URLParams.Add("itemID", "1$2!3") + rCTX.URLParams.Add("permissionID", "permid") + mockProvider.On("GetPermission", mock.Anything, mock.Anything, mock.Anything). + Return(libregraph.Permission{}, errorcode.New(errorcode.ItemNotFound, "permission not found")).Once() + + Expect(get().Code).To(Equal(http.StatusNotFound)) + }) + }) + + Describe("GetSpaceRootPermission", func() { + It("rejects an invalid driveID", func() { + rCTX = chi.NewRouteContext() + rCTX.URLParams.Add("permissionID", "permid") + responseRecorder := httptest.NewRecorder() + request := httptest.NewRequest(http.MethodGet, "/", nil). + WithContext(context.WithValue(context.Background(), chi.RouteCtxKey, rCTX)) + httpAPI.GetSpaceRootPermission(responseRecorder, request) + + Expect(responseRecorder.Code).To(Equal(http.StatusUnprocessableEntity)) + }) + }) +}) + +var _ = Describe("DriveItemPermissions routes", func() { + var ( + graphService svc.Service + gatewayClient *cs3mocks.GatewayAPIClient + ctx context.Context + rr *httptest.ResponseRecorder + ) + + BeforeEach(func() { + ctx = revactx.ContextSetUser(context.Background(), &userpb.User{Id: &userpb.UserId{OpaqueId: "user"}}) + rr = httptest.NewRecorder() + + cfg := defaults.FullDefaultConfig() + cfg.Identity.LDAP.CACert = "" + cfg.TokenManager.JWTSecret = "loremipsum" + cfg.Commons = &shared.Commons{} + cfg.GRPCClientTLS = &shared.GRPCClientTLS{} + + pool.RemoveSelector("GatewaySelector" + "eu.opencloud.api.gateway") + gatewayClient = &cs3mocks.GatewayAPIClient{} + gatewaySelector := pool.GetSelector[gateway.GatewayAPIClient]( + "GatewaySelector", + "eu.opencloud.api.gateway", + func(cc grpc.ClientConnInterface) gateway.GatewayAPIClient { + return gatewayClient + }, + ) + + logger := log.NewLogger() + m, _ := metrics.New(prometheus.NewRegistry(), &logger, func([]string) (string, string) { return "", "" }) + + var err error + graphService, err = svc.NewService( + svc.Config(cfg), + svc.Metrics(m), + svc.WithGatewaySelector(gatewaySelector), + svc.EventsPublisher(&mocks.Publisher{}), + ) + Expect(err).ToNot(HaveOccurred()) + }) + + It("GET .../items/{itemID}/permissions/{permissionID} returns the matching permission", func() { + itemID := &provider.ResourceId{StorageId: "1", SpaceId: "2", OpaqueId: "3"} + gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(&provider.StatResponse{ + Status: status.NewOK(ctx), + Info: &provider.ResourceInfo{ + Id: itemID, + Type: provider.ResourceType_RESOURCE_TYPE_CONTAINER, + PermissionSet: roleconversions.NewEditorRole().CS3ResourcePermissions(), + }, + }, nil) + gatewayClient.On("ListShares", mock.Anything, mock.Anything).Return(&collaboration.ListSharesResponse{Status: status.NewOK(ctx)}, nil) + viewLink := func(id string) *link.PublicShare { + return &link.PublicShare{ + Id: &link.PublicShareId{OpaqueId: id}, + Token: id, + ResourceId: itemID, + Permissions: &link.PublicSharePermissions{Permissions: roleconversions.NewViewerRole().CS3ResourcePermissions()}, + Ctime: &types.Timestamp{Seconds: uint64(time.Now().Unix())}, + } + } + gatewayClient.On("ListPublicShares", mock.Anything, mock.Anything).Return(&link.ListPublicSharesResponse{ + Status: status.NewOK(ctx), + Share: []*link.PublicShare{viewLink("aaaaaaaaaaaaaaa"), viewLink("bbbbbbbbbbbbbbb")}, + }, nil) + + r := httptest.NewRequest(http.MethodGet, "/graph/v1beta1/drives/1$2/items/1$2!3/permissions/bbbbbbbbbbbbbbb", nil).WithContext(ctx) + graphService.ServeHTTP(rr, r) + + Expect(rr.Code).To(Equal(http.StatusOK)) + Expect(gjson.Get(rr.Body.String(), "id").String()).To(Equal("bbbbbbbbbbbbbbb")) + Expect(gjson.Get(rr.Body.String(), "link.type").String()).To(Equal("view")) + }) + + It("GET .../root/permissions/{permissionID} returns the matching permission of a project space", func() { + rootID := &provider.ResourceId{StorageId: "1", SpaceId: "2", OpaqueId: "2"} + gatewayClient.On("ListStorageSpaces", mock.Anything, mock.Anything).Return(&provider.ListStorageSpacesResponse{ + Status: status.NewOK(ctx), + StorageSpaces: []*provider.StorageSpace{{ + Id: &provider.StorageSpaceId{OpaqueId: "1$2"}, + SpaceType: "project", + Root: rootID, + }}, + }, nil) + gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(&provider.StatResponse{ + Status: status.NewOK(ctx), + Info: &provider.ResourceInfo{ + Id: rootID, + Type: provider.ResourceType_RESOURCE_TYPE_CONTAINER, + PermissionSet: roleconversions.NewManagerRole().CS3ResourcePermissions(), + }, + }, nil) + gatewayClient.On("ListShares", mock.Anything, mock.Anything).Return(&collaboration.ListSharesResponse{Status: status.NewOK(ctx)}, nil) + gatewayClient.On("ListPublicShares", mock.Anything, mock.Anything).Return(&link.ListPublicSharesResponse{ + Status: status.NewOK(ctx), + Share: []*link.PublicShare{{ + Id: &link.PublicShareId{OpaqueId: "aaaaaaaaaaaaaaa"}, + Token: "aaaaaaaaaaaaaaa", + ResourceId: rootID, + Permissions: &link.PublicSharePermissions{Permissions: roleconversions.NewViewerRole().CS3ResourcePermissions()}, + }}, + }, nil) + + r := httptest.NewRequest(http.MethodGet, "/graph/v1beta1/drives/1$2/root/permissions/aaaaaaaaaaaaaaa", nil).WithContext(ctx) + graphService.ServeHTTP(rr, r) + + Expect(rr.Code).To(Equal(http.StatusOK)) + Expect(gjson.Get(rr.Body.String(), "id").String()).To(Equal("aaaaaaaaaaaaaaa")) + }) }) func guestGrantee(mail string) *provider.Grantee { diff --git a/services/graph/pkg/service/v0/base.go b/services/graph/pkg/service/v0/base.go index cc25d30da1..7571c64627 100644 --- a/services/graph/pkg/service/v0/base.go +++ b/services/graph/pkg/service/v0/base.go @@ -267,7 +267,8 @@ func (g BaseGraphService) listSpaceRootUserShares(ctx context.Context, filters [ func (g BaseGraphService) listSharesWithSpaceRootFilter(ctx context.Context, spaceRoot bool, filters []*collaboration.Filter, driveItems driveItemsByResourceID) (driveItemsByResourceID, error) { gatewayClient, err := g.gatewaySelector.Next() if err != nil { - g.logger.Error().Err(err).Msg("could not select next gateway client") + logger := g.logger.SubloggerWithRequestID(ctx) + logger.Error().Err(err).Msg("could not select next gateway client") return driveItems, errorcode.New(errorcode.GeneralException, err.Error()) } @@ -299,7 +300,8 @@ func (g BaseGraphService) listSharesWithSpaceRootFilter(ctx context.Context, spa func (g BaseGraphService) listOCMShares(ctx context.Context, filters []*ocm.ListOCMSharesRequest_Filter, driveItems driveItemsByResourceID) (driveItemsByResourceID, error) { gatewayClient, err := g.gatewaySelector.Next() if err != nil { - g.logger.Error().Err(err).Msg("could not select next gateway client") + logger := g.logger.SubloggerWithRequestID(ctx) + logger.Error().Err(err).Msg("could not select next gateway client") return driveItems, errorcode.New(errorcode.GeneralException, err.Error()) } @@ -328,7 +330,8 @@ func (g BaseGraphService) listPublicShares(ctx context.Context, filters []*link. gatewayClient, err := g.gatewaySelector.Next() if err != nil { - g.logger.Error().Err(err).Msg("could not select next gateway client") + logger := g.logger.SubloggerWithRequestID(ctx) + logger.Error().Err(err).Msg("could not select next gateway client") return driveItems, errorcode.New(errorcode.GeneralException, err.Error()) } @@ -815,7 +818,8 @@ func (g BaseGraphService) getLinkPermissionResourceID(ctx context.Context, permi func (g BaseGraphService) getCS3PublicShareByID(ctx context.Context, permissionID string) (*link.PublicShare, error) { gatewayClient, err := g.gatewaySelector.Next() if err != nil { - g.logger.Debug().Err(err).Msg("selecting gatewaySelector failed") + logger := g.logger.SubloggerWithRequestID(ctx) + logger.Error().Err(err).Str(_logKeyPermissionID, permissionID).Msg("selecting gatewaySelector failed") return nil, err } @@ -840,7 +844,8 @@ func (g BaseGraphService) getCS3PublicShareByID(ctx context.Context, permissionI func (g BaseGraphService) removeOCMPermission(ctx context.Context, permissionID string) error { gatewayClient, err := g.gatewaySelector.Next() if err != nil { - g.logger.Debug().Err(err).Msg("selecting gatewaySelector failed") + logger := g.logger.SubloggerWithRequestID(ctx) + logger.Error().Err(err).Str(_logKeyPermissionID, permissionID).Msg("selecting gatewaySelector failed") return err } @@ -866,7 +871,8 @@ func (g BaseGraphService) removeOCMPermission(ctx context.Context, permissionID func (g BaseGraphService) removePublicShare(ctx context.Context, permissionID string) error { gatewayClient, err := g.gatewaySelector.Next() if err != nil { - g.logger.Debug().Err(err).Msg("selecting gatewaySelector failed") + logger := g.logger.SubloggerWithRequestID(ctx) + logger.Error().Err(err).Str(_logKeyPermissionID, permissionID).Msg("selecting gatewaySelector failed") return err } @@ -892,7 +898,8 @@ func (g BaseGraphService) removePublicShare(ctx context.Context, permissionID st func (g BaseGraphService) removeUserShare(ctx context.Context, permissionID string) error { gatewayClient, err := g.gatewaySelector.Next() if err != nil { - g.logger.Debug().Err(err).Msg("selecting gatewaySelector failed") + logger := g.logger.SubloggerWithRequestID(ctx) + logger.Error().Err(err).Str(_logKeyPermissionID, permissionID).Msg("selecting gatewaySelector failed") return err } @@ -927,7 +934,8 @@ func (g BaseGraphService) getOCMPermissionResourceID(ctx context.Context, permis func (g BaseGraphService) getCS3OCMShareByID(ctx context.Context, permissionID string) (*ocm.Share, error) { gatewayClient, err := g.gatewaySelector.Next() if err != nil { - g.logger.Debug().Err(err).Msg("selecting gatewaySelector failed") + logger := g.logger.SubloggerWithRequestID(ctx) + logger.Error().Err(err).Str(_logKeyPermissionID, permissionID).Msg("selecting gatewaySelector failed") return nil, err } @@ -961,7 +969,8 @@ func (g BaseGraphService) getUserPermissionResourceID(ctx context.Context, permi func (g BaseGraphService) getCS3UserShareByID(ctx context.Context, permissionID string) (*collaboration.Share, error) { gatewayClient, err := g.gatewaySelector.Next() if err != nil { - g.logger.Debug().Err(err).Msg("selecting gatewaySelector failed") + logger := g.logger.SubloggerWithRequestID(ctx) + logger.Error().Err(err).Str(_logKeyPermissionID, permissionID).Msg("selecting gatewaySelector failed") return nil, err } @@ -986,7 +995,8 @@ func (g BaseGraphService) getCS3UserShareByID(ctx context.Context, permissionID func (g BaseGraphService) getOCMPermissionByID(ctx context.Context, permissionID string, itemID *storageprovider.ResourceId) (*libregraph.Permission, *storageprovider.ResourceId, error) { gatewayClient, err := g.gatewaySelector.Next() if err != nil { - g.logger.Debug().Err(err).Msg("selecting gatewaySelevtor failed") + logger := g.logger.SubloggerWithRequestID(ctx) + logger.Error().Err(err).Str(_logKeyPermissionID, permissionID).Msg("selecting gatewaySelector failed") return nil, nil, err } @@ -1016,7 +1026,8 @@ func (g BaseGraphService) getOCMPermissionByID(ctx context.Context, permissionID func (g BaseGraphService) getPermissionByID(ctx context.Context, permissionID string, itemID *storageprovider.ResourceId) (*libregraph.Permission, *storageprovider.ResourceId, error) { gatewayClient, err := g.gatewaySelector.Next() if err != nil { - g.logger.Debug().Err(err).Msg("selecting gatewaySelector failed") + logger := g.logger.SubloggerWithRequestID(ctx) + logger.Error().Err(err).Str(_logKeyPermissionID, permissionID).Msg("selecting gatewaySelector failed") return nil, nil, err } publicShare, err := g.getCS3PublicShareByID(ctx, permissionID) @@ -1075,7 +1086,8 @@ func (g BaseGraphService) getPermissionByID(ctx context.Context, permissionID st func (g BaseGraphService) updateOCMPermission(ctx context.Context, permissionID string, itemID *storageprovider.ResourceId, newPermission *libregraph.Permission) (*libregraph.Permission, error) { gatewayClient, err := g.gatewaySelector.Next() if err != nil { - g.logger.Debug().Err(err).Msg("selecting gatewaySelector failed") + logger := g.logger.SubloggerWithRequestID(ctx) + logger.Error().Err(err).Str(_logKeyPermissionID, permissionID).Msg("selecting gatewaySelector failed") return nil, err } @@ -1181,7 +1193,8 @@ func (g BaseGraphService) updateOCMPermission(ctx context.Context, permissionID func (g BaseGraphService) updateUserShare(ctx context.Context, permissionID string, itemID *storageprovider.ResourceId, newPermission *libregraph.Permission) (*libregraph.Permission, error) { gatewayClient, err := g.gatewaySelector.Next() if err != nil { - g.logger.Debug().Err(err).Msg("selecting gatewaySelector failed") + logger := g.logger.SubloggerWithRequestID(ctx) + logger.Error().Err(err).Str(_logKeyPermissionID, permissionID).Msg("selecting gatewaySelector failed") return nil, err } diff --git a/services/graph/pkg/service/v0/driveitems.go b/services/graph/pkg/service/v0/driveitems.go index d20e8cf53f..9d35a437e0 100644 --- a/services/graph/pkg/service/v0/driveitems.go +++ b/services/graph/pkg/service/v0/driveitems.go @@ -493,9 +493,12 @@ func cs3ResourceToDriveItem(logger *log.Logger, publicBaseURL *url.URL, res *sto webURL.Path = path.Join(webURL.Path, "f", storagespace.FormatResourceID(res.GetId())) driveItem.WebUrl = libregraph.PtrString(webURL.String()) - if name := path.Base(res.GetPath()); name != "" { - driveItem.Name = &name + name := res.GetName() + if name == "" { + name = path.Base(res.GetPath()) } + driveItem.Name = &name + if res.GetEtag() != "" { driveItem.ETag = &res.Etag } diff --git a/services/graph/pkg/service/v0/drives.go b/services/graph/pkg/service/v0/drives.go index 954cd0791d..2351e4a6af 100644 --- a/services/graph/pkg/service/v0/drives.go +++ b/services/graph/pkg/service/v0/drives.go @@ -12,6 +12,7 @@ import ( "sort" "strconv" "strings" + "unicode" "github.com/CiscoM31/godata" gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1" @@ -20,6 +21,7 @@ import ( storageprovider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" types "github.com/cs3org/go-cs3apis/cs3/types/v1beta1" "github.com/go-chi/render" + "github.com/google/uuid" libregraph "github.com/opencloud-eu/libre-graph-api-go" revactx "github.com/opencloud-eu/reva/v2/pkg/ctx" "github.com/opencloud-eu/reva/v2/pkg/storagespace" @@ -403,7 +405,7 @@ func (g Graph) CreateDrive(w http.ResponseWriter, r *http.Request) { errorcode.InvalidRequest.Render(w, r, http.StatusBadRequest, "invalid body schema definition") return } - spaceName := strings.TrimSpace(drive.Name) + spaceName := trimSpaceName(drive.Name) if err := validateSpaceName(spaceName); err != nil { log.Debug().Str("name", spaceName).Err(err).Msg("could not create drive: name validation failed") errorcode.InvalidRequest.Render(w, r, http.StatusBadRequest, fmt.Sprintf("invalid spacename: %s", err.Error())) @@ -429,6 +431,28 @@ func (g Graph) CreateDrive(w http.ResponseWriter, r *http.Request) { Quota: getQuota(drive.Quota, g.config.Spaces.DefaultQuota), } + if id := drive.GetId(); id != "" { + // the id ends up in storage paths and in "storageid$spaceid!opaqueid" references, + // so only accept the canonical form of the uuids the storage drivers generate themselves + if u, err := uuid.Parse(id); err != nil || u.String() != id { + log.Debug().Str("id", id).Msg("could not create drive: id is not a canonical uuid") + errorcode.InvalidRequest.Render(w, r, http.StatusBadRequest, "invalid drive id: must be a canonical UUID") + return + } + // personal spaces may use their owner's user id as space id, so an id that belongs to a user + // must not be taken by another space, or that user's personal space could not be created anymore + if _, err := g.identityBackend.GetUser(r.Context(), id, &godata.GoDataRequest{}); err == nil { + log.Debug().Str("id", id).Msg("could not create drive: id belongs to a user") + errorcode.NameAlreadyExists.Render(w, r, http.StatusConflict, "drive already exists") + return + } else if !errorcode.IsErrorCode(err, errorcode.ItemNotFound) { + log.Error().Err(err).Str("id", id).Msg("could not create drive: could not check whether the id belongs to a user") + errorcode.RenderError(w, r, err) + return + } + csr.Opaque = utils.AppendPlainToOpaque(csr.Opaque, "spaceid", id) + } + if drive.Description != nil { csr.Opaque = utils.AppendPlainToOpaque(csr.Opaque, "description", *drive.Description) } @@ -463,6 +487,11 @@ func (g Graph) CreateDrive(w http.ResponseWriter, r *http.Request) { errorcode.InvalidRequest.Render(w, r, http.StatusBadRequest, resp.GetStatus().GetMessage()) return } + if resp.GetStatus().GetCode() == cs3rpc.Code_CODE_ALREADY_EXISTS { + log.Debug().Str("grpcmessage", resp.GetStatus().GetMessage()).Msg("could not create drive: already exists") + errorcode.NameAlreadyExists.Render(w, r, http.StatusConflict, "drive already exists") + return + } log.Debug().Interface("grpcmessage", csr).Str("grpc", resp.GetStatus().GetMessage()).Msg("could not create drive: grpc error") errorcode.GeneralException.Render(w, r, http.StatusInternalServerError, resp.GetStatus().GetMessage()) return @@ -580,8 +609,8 @@ func (g Graph) UpdateDrive(w http.ResponseWriter, r *http.Request) { } } - if drive.GetName() != "" { - spacename := strings.TrimSpace(drive.GetName()) + if _, ok := drive.GetNameOk(); ok { + spacename := trimSpaceName(drive.GetName()) if err := validateSpaceName(spacename); err != nil { log.Info().Err(err).Msg("could not update drive: spacename invalid") errorcode.GeneralException.Render(w, r, http.StatusBadRequest, err.Error()) @@ -1178,6 +1207,18 @@ func sortSpaces(req *godata.GoDataRequest, spaces []*libregraph.Drive) ([]*libre return spaces, nil } +// trimSpaceName removes whitespace and invisible formatting characters from both ends of a +// space name. strings.TrimSpace alone isn't enough: characters such as the zero-width space +// (U+200B), the word joiner (U+2060) or the byte order mark (U+FEFF) aren't whitespace in +// Unicode, but they are invisible, so a name made only of them would look empty in every client. +// Formatting characters inside a name are kept, since some of them are needed there, e.g. the +// zero-width joiner (U+200D) in emoji sequences. +func trimSpaceName(name string) string { + return strings.TrimFunc(name, func(r rune) bool { + return unicode.IsSpace(r) || unicode.Is(unicode.Cf, r) + }) +} + func validateSpaceName(name string) error { if name == "" { return ErrNameEmpty diff --git a/services/graph/pkg/service/v0/drives_test.go b/services/graph/pkg/service/v0/drives_test.go index cfd4fcc0e8..289eeb15c2 100644 --- a/services/graph/pkg/service/v0/drives_test.go +++ b/services/graph/pkg/service/v0/drives_test.go @@ -195,3 +195,31 @@ func TestSpaceNameValidation(t *testing.T) { // set max length back to protect other tests _maxSpaceNameLength = 255 } + +func TestTrimSpaceName(t *testing.T) { + // the names are written as escape sequences on purpose: written directly, these characters + // would be invisible or look like ordinary spaces in the source code + testCases := []struct { + Alias string + SpaceName string + Expected string + }{ + {"Unchanged", "Space", "Space"}, + {"Spaces around", " Space ", "Space"}, + {"Spaces inside are kept", "My Space", "My Space"}, + // U+00A0 no-break space, U+3000 ideographic space + {"Unicode spaces around", "\u00a0Space\u3000", "Space"}, + // U+200B zero-width space, U+FEFF byte order mark + {"Invisible characters around", "\u200bSpace\ufeff", "Space"}, + // U+2060 word joiner, U+2003 em space, U+200E left-to-right mark + {"Mixed around", " \u2060\u2003Space\u200e ", "Space"}, + // U+200D zero-width joiner, as in the emoji sequence of a family + {"Zero-width joiner inside is kept", "Team \U0001F468\u200d\U0001F469\u200d\U0001F467", "Team \U0001F468\u200d\U0001F469\u200d\U0001F467"}, + // U+200B zero-width space, U+200C zero-width non-joiner, U+00A0 no-break space + {"Only invisible characters", "\u200b\u200c\u00a0", ""}, + } + + for _, tc := range testCases { + require.Equal(t, tc.Expected, trimSpaceName(tc.SpaceName), tc.Alias) + } +} diff --git a/services/graph/pkg/service/v0/graph_test.go b/services/graph/pkg/service/v0/graph_test.go index 0b2d2a2d3f..8d0bff30a2 100644 --- a/services/graph/pkg/service/v0/graph_test.go +++ b/services/graph/pkg/service/v0/graph_test.go @@ -8,6 +8,7 @@ import ( "io" "net/http" "net/http/httptest" + "strings" "time" gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1" @@ -28,6 +29,8 @@ import ( "github.com/prometheus/client_golang/prometheus" "github.com/stretchr/testify/mock" "github.com/tidwall/gjson" + sdktrace "go.opentelemetry.io/otel/sdk/trace" + "go.opentelemetry.io/otel/sdk/trace/tracetest" "google.golang.org/grpc" "github.com/opencloud-eu/opencloud/pkg/log" @@ -38,6 +41,8 @@ import ( "github.com/opencloud-eu/opencloud/services/graph/pkg/config" "github.com/opencloud-eu/opencloud/services/graph/pkg/config/defaults" "github.com/opencloud-eu/opencloud/services/graph/pkg/errorcode" + "github.com/opencloud-eu/opencloud/services/graph/pkg/identity" + identitymocks "github.com/opencloud-eu/opencloud/services/graph/pkg/identity/mocks" "github.com/opencloud-eu/opencloud/services/graph/pkg/metrics" service "github.com/opencloud-eu/opencloud/services/graph/pkg/service/v0" "github.com/opencloud-eu/opencloud/services/graph/pkg/unifiedrole" @@ -50,6 +55,7 @@ var _ = Describe("Graph", func() { gatewaySelector pool.Selectable[gateway.GatewayAPIClient] eventsPublisher mocks.Publisher permissionService mocks.Permissions + identityBackend *identitymocks.Backend ctx context.Context cfg *config.Config rr *httptest.ResponseRecorder @@ -86,6 +92,7 @@ var _ = Describe("Graph", func() { eventsPublisher = mocks.Publisher{} permissionService = mocks.Permissions{} + identityBackend = &identitymocks.Backend{} var err error svc, err = service.NewService( @@ -94,6 +101,7 @@ var _ = Describe("Graph", func() { service.WithGatewaySelector(gatewaySelector), service.EventsPublisher(&eventsPublisher), service.PermissionService(&permissionService), + service.WithIdentityBackend(identityBackend), ) Expect(err).ToNot(HaveOccurred()) }) @@ -104,6 +112,48 @@ var _ = Describe("Graph", func() { }) }) + Describe("permissions tracing", func() { + It("records a span for the permissions service when a TraceProvider is configured", func() { + sr := tracetest.NewSpanRecorder() + tp := sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(sr)) + DeferCleanup(func() { + Expect(tp.Shutdown(context.Background())).To(Succeed()) + }) + + logger := log.NewLogger() + m, err := metrics.New(prometheus.NewRegistry(), &logger, func([]string) (string, string) { return "", "" }) + Expect(err).ToNot(HaveOccurred()) + tracedSvc, err := service.NewService( + service.Config(cfg), + service.Metrics(m), + service.WithGatewaySelector(gatewaySelector), + service.EventsPublisher(&eventsPublisher), + service.PermissionService(&permissionService), + service.TraceProvider(tp), + ) + Expect(err).ToNot(HaveOccurred()) + + gatewayClient.On("ListStorageSpaces", mock.Anything, mock.Anything).Return(&provider.ListStorageSpacesResponse{ + Status: status.NewOK(ctx), + }, nil) + + r := httptest.NewRequest(http.MethodGet, "/graph/v1beta1/drives/1$2/root/permissions", nil).WithContext(ctx) + tracedSvc.ServeHTTP(rr, r) + + // the request was routed to the permissions service, which looked up the space + Expect(rr.Code).To(Equal(http.StatusNotFound)) + gatewayClient.AssertCalled(GinkgoT(), "ListStorageSpaces", mock.Anything, mock.Anything) + // http tracing works with this provider + Expect(sr.Ended()).ToNot(BeEmpty()) + + var names []string + for _, s := range sr.Ended() { + names = append(names, s.Name()) + } + Expect(names).To(ContainElement("ListSpaceRootPermissions")) + }) + }) + Describe("Drives", func() { Describe("GetDrivesV1 and GetAllDrivesV1", func() { BeforeEach(func() { @@ -843,6 +893,156 @@ var _ = Describe("Graph", func() { Expect(*response.Description).To(Equal("This space is for testing")) Expect(*response.LibreGraphContentType).To(Equal("application/vnd.opencloud.test")) }) + Context("drive id handling", func() { + const spaceID = "0b9a7b84-3e71-4a4e-9c34-0e6a4c3f5f21" + + // csr captures the request the handler sends to the gateway + var csr *provider.CreateStorageSpaceRequest + mockSuccessfulCreate := func(createdSpaceID string) { + gatewayClient.On("CreateStorageSpace", mock.Anything, mock.Anything).Run(func(args mock.Arguments) { + csr = args.Get(1).(*provider.CreateStorageSpaceRequest) + }).Return(&provider.CreateStorageSpaceResponse{ + Status: status.NewOK(ctx), + StorageSpace: &provider.StorageSpace{ + Id: &provider.StorageSpaceId{OpaqueId: "pro-1$" + createdSpaceID}, + Name: "Test Space", + SpaceType: "project", + Root: &provider.ResourceId{StorageId: "pro-1", SpaceId: createdSpaceID, OpaqueId: createdSpaceID}, + }, + }, nil) + gatewayClient.On("GetQuota", mock.Anything, mock.Anything).Return(&provider.GetQuotaResponse{ + Status: status.NewOK(ctx), + TotalBytes: 500, + }, nil) + } + + BeforeEach(func() { + csr = 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) + }) + + DescribeTable("lets the storage provider generate the id when none is supplied, without looking up users", + func(jsonBody string) { + mockSuccessfulCreate("generated-id") + + r := httptest.NewRequest(http.MethodPost, "/graph/v1.0/drives", bytes.NewBufferString(jsonBody)).WithContext(ctx) + rr := httptest.NewRecorder() + svc.CreateDrive(rr, r) + Expect(rr.Code).To(Equal(http.StatusCreated)) + Expect(csr).ToNot(BeNil()) + Expect(csr.GetOpaque().GetMap()).ToNot(HaveKey("spaceid")) + identityBackend.AssertNotCalled(GinkgoT(), "GetUser", mock.Anything, mock.Anything, mock.Anything) + }, + Entry("absent id", `{"name": "Test Space"}`), + Entry("empty id", `{"name": "Test Space", "id": ""}`), + ) + + It("forwards the id to the storage provider when it does not belong to a user", func() { + identityBackend.On("GetUser", mock.Anything, spaceID, mock.Anything).Return(nil, identity.ErrNotFound) + mockSuccessfulCreate(spaceID) + + jsonBody := []byte(`{"name": "Test Space", "id": "` + spaceID + `"}`) + 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)) + Expect(utils.ReadPlainFromOpaque(csr.GetOpaque(), "spaceid")).To(Equal(spaceID)) + + var response libregraph.Drive + Expect(json.Unmarshal(rr.Body.Bytes(), &response)).To(Succeed()) + Expect(response.GetId()).To(Equal("pro-1$" + spaceID)) + identityBackend.AssertCalled(GinkgoT(), "GetUser", mock.Anything, spaceID, mock.Anything) + }) + + // In the next two tests a successful CreateStorageSpace is mocked on purpose: a handler that + // skips the user lookup then fails on the status and AssertNotCalled checks, not on an + // unexpected mock call. + It("returns 409 Conflict without creating the space when the id belongs to a user", func() { + identityBackend.On("GetUser", mock.Anything, spaceID, mock.Anything).Return(&libregraph.User{Id: libregraph.PtrString(spaceID)}, nil) + mockSuccessfulCreate(spaceID) + + jsonBody := []byte(`{"name": "Test Space", "id": "` + spaceID + `"}`) + 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.StatusConflict)) + + var libreError libregraph.OdataError + Expect(json.Unmarshal(rr.Body.Bytes(), &libreError)).To(Succeed()) + Expect(libreError.Error.Code).To(Equal(errorcode.NameAlreadyExists.String())) + Expect(libreError.Error.Message).To(Equal("drive already exists")) + gatewayClient.AssertNotCalled(GinkgoT(), "CreateStorageSpace", mock.Anything, mock.Anything) + }) + + It("does not create the space when the identity backend fails to look up the id", func() { + identityBackend.On("GetUser", mock.Anything, spaceID, mock.Anything).Return(nil, errorcode.New(errorcode.ServiceNotAvailable, "identity backend unavailable")) + mockSuccessfulCreate(spaceID) + + jsonBody := []byte(`{"name": "Test Space", "id": "` + spaceID + `"}`) + 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.StatusInternalServerError)) + + var libreError libregraph.OdataError + Expect(json.Unmarshal(rr.Body.Bytes(), &libreError)).To(Succeed()) + Expect(libreError.Error.Code).To(Equal(errorcode.ServiceNotAvailable.String())) + gatewayClient.AssertNotCalled(GinkgoT(), "CreateStorageSpace", mock.Anything, mock.Anything) + }) + + DescribeTable("rejects ids that are not canonical UUIDs before looking up users or calling the storage provider", + func(id string) { + gatewayClient.On("CreateStorageSpace", mock.Anything, mock.Anything).Return(&provider.CreateStorageSpaceResponse{ + Status: status.NewInternal(ctx, "storage provider must not be called"), + }, nil).Maybe() + + body, err := json.Marshal(map[string]string{"name": "Test Space", "id": id}) + Expect(err).ToNot(HaveOccurred()) + r := httptest.NewRequest(http.MethodPost, "/graph/v1.0/drives", bytes.NewBuffer(body)).WithContext(ctx) + rr := httptest.NewRecorder() + svc.CreateDrive(rr, r) + Expect(rr.Code).To(Equal(http.StatusBadRequest)) + + var libreError libregraph.OdataError + Expect(json.Unmarshal(rr.Body.Bytes(), &libreError)).To(Succeed()) + Expect(libreError.Error.Code).To(Equal(errorcode.InvalidRequest.String())) + Expect(libreError.Error.Message).To(Equal("invalid drive id: must be a canonical UUID")) + identityBackend.AssertNotCalled(GinkgoT(), "GetUser", mock.Anything, mock.Anything, mock.Anything) + gatewayClient.AssertNotCalled(GinkgoT(), "CreateStorageSpace", mock.Anything, mock.Anything) + }, + Entry("path traversal", "../../x"), + Entry("storage id delimiter", "pro-1$"+spaceID), + Entry("opaque id delimiter", spaceID+"!"+spaceID), + Entry("arbitrary string", "not-a-uuid"), + Entry("uppercase", strings.ToUpper(spaceID)), + Entry("braces", "{"+spaceID+"}"), + Entry("urn", "urn:uuid:"+spaceID), + Entry("no hyphens", strings.ReplaceAll(spaceID, "-", "")), + ) + + It("returns 409 Conflict when the storage provider reports that the space already exists", func() { + identityBackend.On("GetUser", mock.Anything, spaceID, mock.Anything).Return(nil, identity.ErrNotFound) + gatewayClient.On("CreateStorageSpace", mock.Anything, mock.Anything).Return(&provider.CreateStorageSpaceResponse{ + Status: status.NewAlreadyExists(ctx, nil, "decomposedfs: spaces: space already exists"), + }, nil) + + jsonBody := []byte(`{"name": "Test Space", "id": "` + spaceID + `"}`) + 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.StatusConflict)) + + var libreError libregraph.OdataError + Expect(json.Unmarshal(rr.Body.Bytes(), &libreError)).To(Succeed()) + Expect(libreError.Error.Code).To(Equal(errorcode.NameAlreadyExists.String())) + Expect(libreError.Error.Message).To(Equal("drive already exists")) + }) + }) It("Incomplete space", func() { gatewayClient.On("CreateStorageSpace", mock.Anything, mock.Anything).Return(&provider.CreateStorageSpaceResponse{ Status: status.NewOK(ctx), @@ -1177,6 +1377,67 @@ var _ = Describe("Graph", func() { })) }) + DescribeTable("rejects an invalid name without updating the space", + func(name string) { + body, err := json.Marshal(map[string]string{"name": name}) + Expect(err).ToNot(HaveOccurred()) + r := httptest.NewRequest(http.MethodPatch, "/graph/v1.0/drives/{driveID}/", bytes.NewBuffer(body)) + rctx := chi.NewRouteContext() + rctx.URLParams.Add("driveID", "spaceid") + r = r.WithContext(context.WithValue(revactx.ContextSetUser(ctx, nil), chi.RouteCtxKey, rctx)) + svc.UpdateDrive(rr, r) + Expect(rr.Code).To(Equal(http.StatusBadRequest)) + + gatewayClient.AssertNotCalled(GinkgoT(), "UpdateStorageSpace", mock.Anything, mock.Anything) + }, + // the names are written as escape sequences on purpose: written directly, these + // characters would be invisible or look like ordinary spaces in the source code + Entry("empty name", ""), + Entry("name of only spaces", " "), + Entry("name of only tabs and line breaks", "\t\n\r"), + // U+00A0 no-break space, U+202F narrow no-break space + Entry("name of only no-break spaces", "\u00a0\u202f"), + // U+2003 em space, U+2009 thin space, U+3000 ideographic space + Entry("name of only wide spaces", "\u2003\u2009\u3000"), + // U+200B zero-width space: invisible, but not whitespace in Unicode + Entry("name of only zero-width spaces", "\u200b\u200b"), + // U+200C zero-width non-joiner, U+200D zero-width joiner + Entry("name of only zero-width joiners", "\u200c\u200d"), + // U+2060 word joiner, U+FEFF byte order mark (zero-width no-break space) + Entry("name of only a word joiner and a byte order mark", "\u2060\ufeff"), + // space, U+200B zero-width space, U+00A0 no-break space, U+FEFF byte order mark, space + Entry("name of mixed invisible characters", " \u200b\u00a0\ufeff "), + ) + + DescribeTable("keeps the name when the request doesn't set one", + func(jsonBody string) { + gatewayClient.On("UpdateStorageSpace", mock.Anything, mock.Anything).Return(func(_ context.Context, req *provider.UpdateStorageSpaceRequest, _ ...grpc.CallOption) *provider.UpdateStorageSpaceResponse { + return &provider.UpdateStorageSpaceResponse{ + Status: status.NewOK(ctx), + StorageSpace: req.StorageSpace, + } + }, nil) + gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(&provider.StatResponse{ + Status: status.NewNotFound(ctx, "no special files found"), + }, nil).Maybe() + + r := httptest.NewRequest(http.MethodPatch, "/graph/v1.0/drives/{driveID}/", bytes.NewBufferString(jsonBody)) + rctx := chi.NewRouteContext() + rctx.URLParams.Add("driveID", "spaceid") + r = r.WithContext(context.WithValue(revactx.ContextSetUser(ctx, nil), chi.RouteCtxKey, rctx)) + svc.UpdateDrive(rr, r) + Expect(rr.Code).To(Equal(http.StatusOK)) + + gatewayClient.AssertCalled(GinkgoT(), "UpdateStorageSpace", mock.Anything, mock.MatchedBy(func(req *provider.UpdateStorageSpaceRequest) bool { + return req.StorageSpace.Id.OpaqueId == "spaceid" && + req.StorageSpace.Name == "" && + utils.ReadPlainFromOpaque(req.StorageSpace.Opaque, "description") == "thedescription" + })) + }, + Entry("no name", `{"description": "thedescription"}`), + Entry("null name", `{"name": null, "description": "thedescription"}`), + ) + It("restores", func() { drive := libregraph.NewDrive("thename") driveJson, err := json.Marshal(drive) diff --git a/services/graph/pkg/service/v0/loglevel_test.go b/services/graph/pkg/service/v0/loglevel_test.go new file mode 100644 index 0000000000..3fcdfd402f --- /dev/null +++ b/services/graph/pkg/service/v0/loglevel_test.go @@ -0,0 +1,259 @@ +package svc + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "testing" + + gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1" + storageprovider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" + "github.com/go-chi/chi/v5/middleware" + libregraph "github.com/opencloud-eu/libre-graph-api-go" + "github.com/opencloud-eu/reva/v2/pkg/rgrpc/todo/pool" + "github.com/rs/zerolog" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/opencloud-eu/opencloud/pkg/log" + "github.com/opencloud-eu/opencloud/services/graph/pkg/errorcode" +) + +// logEntry logs one event with fn into a buffer and returns the decoded entry. +func logEntry(t *testing.T, fn func(logger *log.Logger) *zerolog.Event) map[string]any { + t.Helper() + var buf bytes.Buffer + logger := &log.Logger{Logger: zerolog.New(&buf)} + fn(logger).Msg("test") + var entry map[string]any + require.NoError(t, json.Unmarshal(buf.Bytes(), &entry)) + return entry +} + +func TestErrorEvent(t *testing.T) { + t.Run("unexpected failure: error level with the error text", func(t *testing.T) { + err := errorcode.New(errorcode.GeneralException, "share manager unavailable") + entry := logEntry(t, func(l *log.Logger) *zerolog.Event { return errorEvent(l, err) }) + assert.Equal(t, "error", entry["level"]) + assert.Equal(t, "generalException", entry["errorCode"]) + assert.Equal(t, err.Error(), entry["error"]) + }) + t.Run("expected client error: debug level with the error text", func(t *testing.T) { + err := errorcode.New(errorcode.ItemNotFound, "share not found") + entry := logEntry(t, func(l *log.Logger) *zerolog.Event { return errorEvent(l, err) }) + assert.Equal(t, "debug", entry["level"]) + assert.Equal(t, "itemNotFound", entry["errorCode"]) + assert.Equal(t, err.Error(), entry["error"]) + }) +} + +func TestFallbackErrorEvent(t *testing.T) { + notFound := errorcode.New(errorcode.ItemNotFound, "not found") + failure := errorcode.New(errorcode.GeneralException, "share manager unavailable") + + t.Run("the other attempt failed unexpectedly: error level, both texts", func(t *testing.T) { + entry := logEntry(t, func(l *log.Logger) *zerolog.Event { return fallbackErrorEvent(l, notFound, failure, "lookupError") }) + assert.Equal(t, "error", entry["level"]) + assert.Equal(t, "itemNotFound", entry["errorCode"]) + assert.Equal(t, notFound.Error(), entry["error"]) + assert.Equal(t, "generalException", entry["lookupErrorCode"]) + assert.Equal(t, failure.Error(), entry["lookupError"]) + }) + t.Run("the returned error is unexpected: error level, both texts", func(t *testing.T) { + entry := logEntry(t, func(l *log.Logger) *zerolog.Event { return fallbackErrorEvent(l, failure, notFound, "lookupError") }) + assert.Equal(t, "error", entry["level"]) + assert.Equal(t, failure.Error(), entry["error"]) + assert.Equal(t, "itemNotFound", entry["lookupErrorCode"]) + assert.Equal(t, notFound.Error(), entry["lookupError"]) + }) + t.Run("both attempts failed expectedly: debug level, both texts", func(t *testing.T) { + entry := logEntry(t, func(l *log.Logger) *zerolog.Event { return fallbackErrorEvent(l, notFound, notFound, "lookupError") }) + assert.Equal(t, "debug", entry["level"]) + assert.Equal(t, notFound.Error(), entry["error"]) + assert.Equal(t, notFound.Error(), entry["lookupError"]) + }) + t.Run("without another attempt: like errorEvent", func(t *testing.T) { + entry := logEntry(t, func(l *log.Logger) *zerolog.Event { return fallbackErrorEvent(l, failure, nil, "lookupError") }) + assert.Equal(t, "error", entry["level"]) + assert.Equal(t, failure.Error(), entry["error"]) + assert.NotContains(t, entry, "lookupErrorCode") + }) +} + +// failingGatewaySelector is a gateway selector that never finds a gateway. +type failingGatewaySelector struct{ err error } + +func (s failingGatewaySelector) Next(...pool.Option) (gateway.GatewayAPIClient, error) { + return nil, s.err +} + +// TestHelperGatewaySelectionFailureIsLoggedAsError checks that every helper that selects a gateway on its +// own logs a failed selection at error level with the selector's error, whichever operation calls it. +// The entry carries the request id, so it can be matched with the entry of the calling operation, +// and the permission id when the helper works on a single permission. +func TestHelperGatewaySelectionFailureIsLoggedAsError(t *testing.T) { + const listMsg = "could not select next gateway client" + const lookupMsg = "selecting gatewaySelector failed" + const requestID = "request-42" + const permissionID = "permissionid" + ctx := context.WithValue(context.Background(), middleware.RequestIDKey, requestID) + itemID := &storageprovider.ResourceId{StorageId: "1", SpaceId: "2", OpaqueId: "3"} + + tests := []struct { + name string + message string + permissionID string + call func(s DriveItemPermissionsService) error + }{ + {"listSharesWithSpaceRootFilter", listMsg, "", func(s DriveItemPermissionsService) error { + _, err := s.listSharesWithSpaceRootFilter(ctx, false, nil, driveItemsByResourceID{}) + return err + }}, + {"listOCMShares", listMsg, "", func(s DriveItemPermissionsService) error { + _, err := s.listOCMShares(ctx, nil, driveItemsByResourceID{}) + return err + }}, + {"listPublicShares", listMsg, "", func(s DriveItemPermissionsService) error { + _, err := s.listPublicShares(ctx, nil, driveItemsByResourceID{}) + return err + }}, + {"updatePublicLinkPermission", listMsg, permissionID, func(s DriveItemPermissionsService) error { + _, err := s.updatePublicLinkPermission(ctx, permissionID, itemID, &libregraph.Permission{}) + return err + }}, + {"getCS3PublicShareByID", lookupMsg, permissionID, func(s DriveItemPermissionsService) error { + _, err := s.getCS3PublicShareByID(ctx, permissionID) + return err + }}, + {"getCS3UserShareByID", lookupMsg, permissionID, func(s DriveItemPermissionsService) error { + _, err := s.getCS3UserShareByID(ctx, permissionID) + return err + }}, + {"getCS3OCMShareByID", lookupMsg, permissionID, func(s DriveItemPermissionsService) error { + _, err := s.getCS3OCMShareByID(ctx, permissionID) + return err + }}, + {"getPermissionByID", lookupMsg, permissionID, func(s DriveItemPermissionsService) error { + _, _, err := s.getPermissionByID(ctx, permissionID, itemID) + return err + }}, + {"getOCMPermissionByID", lookupMsg, permissionID, func(s DriveItemPermissionsService) error { + _, _, err := s.getOCMPermissionByID(ctx, permissionID, itemID) + return err + }}, + {"removeUserShare", lookupMsg, permissionID, func(s DriveItemPermissionsService) error { + return s.removeUserShare(ctx, permissionID) + }}, + {"removePublicShare", lookupMsg, permissionID, func(s DriveItemPermissionsService) error { + return s.removePublicShare(ctx, permissionID) + }}, + {"removeOCMPermission", lookupMsg, permissionID, func(s DriveItemPermissionsService) error { + return s.removeOCMPermission(ctx, permissionID) + }}, + {"updateUserShare", lookupMsg, permissionID, func(s DriveItemPermissionsService) error { + _, err := s.updateUserShare(ctx, permissionID, itemID, &libregraph.Permission{}) + return err + }}, + {"updateOCMPermission", lookupMsg, permissionID, func(s DriveItemPermissionsService) error { + _, err := s.updateOCMPermission(ctx, permissionID, itemID, &libregraph.Permission{}) + return err + }}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + var buf bytes.Buffer + s := DriveItemPermissionsService{BaseGraphService: BaseGraphService{ + logger: &log.Logger{Logger: zerolog.New(&buf)}, + gatewaySelector: failingGatewaySelector{err: errors.New("no gateway available")}, + }} + + require.Error(t, tc.call(s)) + + var entry map[string]any + require.NoError(t, json.Unmarshal(buf.Bytes(), &entry), "exactly one log entry") + assert.Equal(t, "error", entry["level"]) + assert.Equal(t, tc.message, entry["message"]) + assert.Equal(t, "no gateway available", entry["error"]) + assert.Equal(t, requestID, entry[log.RequestIDString]) + if tc.permissionID != "" { + assert.Equal(t, tc.permissionID, entry[_logKeyPermissionID]) + } else { + assert.NotContains(t, entry, _logKeyPermissionID) + } + }) + } +} + +func TestLogLevelForError(t *testing.T) { + tests := []struct { + name string + err error + want zerolog.Level + }{ + // expected client errors, rendered as 4xx by errorcode.Error.Render + {"item not found", errorcode.New(errorcode.ItemNotFound, "x"), zerolog.DebugLevel}, + {"access denied", errorcode.New(errorcode.AccessDenied, "x"), zerolog.DebugLevel}, + {"invalid request", errorcode.New(errorcode.InvalidRequest, "x"), zerolog.DebugLevel}, + {"name already exists", errorcode.New(errorcode.NameAlreadyExists, "x"), zerolog.DebugLevel}, + {"invalid range", errorcode.New(errorcode.InvalidRange, "x"), zerolog.DebugLevel}, + {"item is locked", errorcode.New(errorcode.ItemIsLocked, "x"), zerolog.DebugLevel}, + {"precondition failed", errorcode.New(errorcode.PreconditionFailed, "x"), zerolog.DebugLevel}, + {"not allowed", errorcode.New(errorcode.NotAllowed, "x"), zerolog.DebugLevel}, + {"wrapped item not found", fmt.Errorf("lookup: %w", errorcode.New(errorcode.ItemNotFound, "x")), zerolog.DebugLevel}, + {"wrapped access denied", fmt.Errorf("lookup: %w", errorcode.New(errorcode.AccessDenied, "x")), zerolog.DebugLevel}, + + // unexpected server-side failures + {"general exception", errorcode.New(errorcode.GeneralException, "x"), zerolog.ErrorLevel}, + {"service not available", errorcode.New(errorcode.ServiceNotAvailable, "x"), zerolog.ErrorLevel}, + {"unauthenticated", errorcode.New(errorcode.Unauthenticated, "x"), zerolog.ErrorLevel}, + {"quota limit reached", errorcode.New(errorcode.QuotaLimitReached, "x"), zerolog.ErrorLevel}, + {"not supported", errorcode.New(errorcode.NotSupported, "x"), zerolog.ErrorLevel}, + {"wrapped general exception", fmt.Errorf("stat: %w", errorcode.New(errorcode.GeneralException, "x")), zerolog.ErrorLevel}, + {"plain error", errors.New("connection refused"), zerolog.ErrorLevel}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + assert.Equal(t, tc.want, logLevelForError(tc.err)) + }) + } +} + +func TestErrorCodeForError(t *testing.T) { + tests := []struct { + name string + err error + want string + }{ + {"graph error", errorcode.New(errorcode.ItemNotFound, "private-file.txt"), "itemNotFound"}, + {"wrapped graph error", fmt.Errorf("stat: %w", errorcode.New(errorcode.ServiceNotAvailable, "x")), "serviceNotAvailable"}, + // errorcode.RenderError renders untyped errors as generalException + {"plain error", errors.New("connection refused"), "generalException"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + assert.Equal(t, tc.want, errorCodeForError(tc.err)) + }) + } +} + +// TestLogLevelForErrorMatchesRenderedStatus keeps logLevelForError in sync with errorcode.Error.Render: +// every code rendered as a 4xx is an expected client error, everything else is unexpected. +func TestLogLevelForErrorMatchesRenderedStatus(t *testing.T) { + // ItemIsLocked is the last declared error code + for code := errorcode.AccessDenied; code <= errorcode.ItemIsLocked; code++ { + t.Run(code.String(), func(t *testing.T) { + rr := httptest.NewRecorder() + errorcode.New(code, "x").Render(rr, httptest.NewRequest(http.MethodGet, "/", nil)) + + want := zerolog.ErrorLevel + if rr.Code >= http.StatusBadRequest && rr.Code < http.StatusInternalServerError { + want = zerolog.DebugLevel + } + assert.Equal(t, want, logLevelForError(errorcode.New(code, "x")), "rendered status %d", rr.Code) + }) + } +} diff --git a/services/graph/pkg/service/v0/service.go b/services/graph/pkg/service/v0/service.go index 65e0d39305..9dd651f346 100644 --- a/services/graph/pkg/service/v0/service.go +++ b/services/graph/pkg/service/v0/service.go @@ -167,7 +167,7 @@ func NewService(opts ...Option) (Graph, error) { //nolint:maintidx return Graph{}, err } - driveItemPermissionsService, err := NewDriveItemPermissionsService(options.Logger, options.GatewaySelector, identityCache, options.Config) + driveItemPermissionsService, err := NewDriveItemPermissionsService(options.Logger, options.GatewaySelector, identityCache, options.Config, options.TraceProvider) if err != nil { return Graph{}, err } @@ -264,6 +264,7 @@ func NewService(opts ...Option) (Graph, error) { //nolint:maintidx r.Route("/permissions", func(r chi.Router) { r.Get("/", driveItemPermissionsApi.ListSpaceRootPermissions) r.Route("/{permissionID}", func(r chi.Router) { + r.Get("/", driveItemPermissionsApi.GetSpaceRootPermission) r.Delete("/", driveItemPermissionsApi.DeleteSpaceRootPermission) r.Patch("/", driveItemPermissionsApi.UpdateSpaceRootPermission) r.Post("/setPassword", driveItemPermissionsApi.SetSpaceRootLinkPassword) @@ -279,6 +280,7 @@ func NewService(opts ...Option) (Graph, error) { //nolint:maintidx r.Route("/permissions", func(r chi.Router) { r.Get("/", driveItemPermissionsApi.ListPermissions) r.Route("/{permissionID}", func(r chi.Router) { + r.Get("/", driveItemPermissionsApi.GetPermission) r.Delete("/", driveItemPermissionsApi.DeletePermission) r.Patch("/", driveItemPermissionsApi.UpdatePermission) r.Post("/setPassword", driveItemPermissionsApi.SetLinkPassword) diff --git a/services/graph/pkg/service/v0/sharedbyme.go b/services/graph/pkg/service/v0/sharedbyme.go index 011bf94d80..14afeec381 100644 --- a/services/graph/pkg/service/v0/sharedbyme.go +++ b/services/graph/pkg/service/v0/sharedbyme.go @@ -7,7 +7,9 @@ import ( rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1" "github.com/go-chi/render" libregraph "github.com/opencloud-eu/libre-graph-api-go" + revactx "github.com/opencloud-eu/reva/v2/pkg/ctx" + "github.com/opencloud-eu/opencloud/pkg/log" "github.com/opencloud-eu/opencloud/services/graph/pkg/errorcode" ) @@ -15,11 +17,15 @@ type driveItemsByResourceID map[string]libregraph.DriveItem // GetSharedByMe implements the Service interface (/me/drives/sharedByMe endpoint) func (g Graph) GetSharedByMe(w http.ResponseWriter, r *http.Request) { - g.logger.Debug().Msg("Calling GetRootDriveChildren") ctx := r.Context() + logger := g.logger.SubloggerWithRequestID(ctx) + if user, ok := revactx.ContextGetUser(ctx); ok { + logger = log.Logger{Logger: logger.With().Str(_logKeyUserID, user.GetId().GetOpaqueId()).Logger()} + } driveItems, err := g.listUserShares(ctx, nil, make(driveItemsByResourceID)) if err != nil { + errorEvent(&logger, err).Msg("could not list user shares") errorcode.RenderError(w, r, err) return } @@ -27,6 +33,7 @@ func (g Graph) GetSharedByMe(w http.ResponseWriter, r *http.Request) { if g.config.IncludeOCMSharees { driveItems, err = g.listOCMShares(ctx, nil, driveItems) if err != nil { + errorEvent(&logger, err).Msg("could not list ocm shares") errorcode.RenderError(w, r, err) return } @@ -34,6 +41,7 @@ func (g Graph) GetSharedByMe(w http.ResponseWriter, r *http.Request) { driveItems, err = g.listPublicShares(ctx, nil, driveItems) if err != nil { + errorEvent(&logger, err).Msg("could not list public shares") errorcode.RenderError(w, r, err) return } diff --git a/services/graph/pkg/service/v0/sharedbyme_test.go b/services/graph/pkg/service/v0/sharedbyme_test.go index a42b8177f8..a33c116cd4 100644 --- a/services/graph/pkg/service/v0/sharedbyme_test.go +++ b/services/graph/pkg/service/v0/sharedbyme_test.go @@ -1,6 +1,7 @@ package svc_test import ( + "bytes" "context" "encoding/json" "errors" @@ -14,17 +15,21 @@ import ( userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" collaboration "github.com/cs3org/go-cs3apis/cs3/sharing/collaboration/v1beta1" link "github.com/cs3org/go-cs3apis/cs3/sharing/link/v1beta1" + ocm "github.com/cs3org/go-cs3apis/cs3/sharing/ocm/v1beta1" provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" + "github.com/go-chi/chi/v5/middleware" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" libregraph "github.com/opencloud-eu/libre-graph-api-go" "github.com/opencloud-eu/reva/v2/pkg/conversions" + revactx "github.com/opencloud-eu/reva/v2/pkg/ctx" "github.com/opencloud-eu/reva/v2/pkg/rgrpc/status" "github.com/opencloud-eu/reva/v2/pkg/rgrpc/todo/pool" "github.com/opencloud-eu/reva/v2/pkg/storagespace" "github.com/opencloud-eu/reva/v2/pkg/utils" cs3mocks "github.com/opencloud-eu/reva/v2/tests/cs3mocks/mocks" "github.com/prometheus/client_golang/prometheus" + "github.com/rs/zerolog" "github.com/stretchr/testify/mock" "google.golang.org/grpc" @@ -33,6 +38,7 @@ import ( "github.com/opencloud-eu/opencloud/services/graph/mocks" "github.com/opencloud-eu/opencloud/services/graph/pkg/config" "github.com/opencloud-eu/opencloud/services/graph/pkg/config/defaults" + "github.com/opencloud-eu/opencloud/services/graph/pkg/errorcode" identitymocks "github.com/opencloud-eu/opencloud/services/graph/pkg/identity/mocks" "github.com/opencloud-eu/opencloud/services/graph/pkg/linktype" "github.com/opencloud-eu/opencloud/services/graph/pkg/metrics" @@ -279,6 +285,260 @@ var _ = Describe("sharedbyme", func() { nil, ) } + Describe("GetSharedByMe logging", func() { + var logBuf *bytes.Buffer + + newLoggedService := func(selector pool.Selectable[gateway.GatewayAPIClient]) service.Service { + logBuf = &bytes.Buffer{} + logger := log.NewLogger() + m, err := metrics.New(prometheus.NewRegistry(), &logger, func([]string) (string, string) { return "", "" }) + Expect(err).ToNot(HaveOccurred()) + s, err := service.NewService( + service.Config(cfg), + service.Metrics(m), + service.WithGatewaySelector(selector), + service.EventsPublisher(&eventsPublisher), + service.WithIdentityBackend(identityBackend), + service.Logger(log.Logger{Logger: zerolog.New(logBuf)}), + ) + Expect(err).ToNot(HaveOccurred()) + return s + } + errorEntries := func() []map[string]any { + return entriesAtLevel(logEntries(logBuf), "error") + } + odataError := func() libregraph.OdataError { + var odataErr libregraph.OdataError + Expect(json.Unmarshal(rr.Body.Bytes(), &odataErr)).To(Succeed()) + return odataErr + } + + It("logs a gateway selection failure while listing shares as error in the helper and the operation", func() { + failingSelector := mocks.NewSelectable[gateway.GatewayAPIClient](GinkgoT()) + failingSelector.EXPECT().Next().Return(nil, errors.New("no gateway available")) + s := newLoggedService(failingSelector) + + s.GetSharedByMe(rr, httptest.NewRequest(http.MethodGet, "/graph/v1.0/me/drives/sharedByMe", nil)) + + Expect(rr.Code).To(Equal(http.StatusInternalServerError)) + Expect(odataError().Error.Code).To(Equal("generalException")) + Expect(odataError().Error.Message).To(Equal("no gateway available")) + // the helper and the handler both log the reason, the handler with the error code + Expect(errorEntries()).To(ConsistOf( + gatewayHelperEntry("could not select next gateway client", "no gateway available"), + SatisfyAll( + HaveKeyWithValue("message", "could not list user shares"), + HaveKeyWithValue("errorCode", "generalException"), + HaveKeyWithValue("error", errorcode.New(errorcode.GeneralException, "no gateway available").Error()), + ), + )) + }) + + It("logs a share listing failure once as error", func() { + emptyListPublicSharesMock() + gatewayClient.On("ListShares", mock.Anything, mock.Anything).Return( + &collaboration.ListSharesResponse{Status: status.NewInternal(ctx, "error listing shares")}, + nil, + ) + s := newLoggedService(gatewaySelector) + + r := httptest.NewRequest(http.MethodGet, "/graph/v1.0/me/drives/sharedByMe", nil) + reqCtx := context.WithValue(r.Context(), middleware.RequestIDKey, "request-42") + reqCtx = revactx.ContextSetUser(reqCtx, &userpb.User{Id: &userpb.UserId{OpaqueId: "user-42"}}) + s.GetSharedByMe(rr, r.WithContext(reqCtx)) + + Expect(rr.Code).To(Equal(http.StatusInternalServerError)) + Expect(odataError().Error.Code).To(Equal("generalException")) + Expect(odataError().Error.Message).To(Equal("error listing shares")) + entries := errorEntries() + Expect(entries).To(HaveLen(1)) + Expect(entries[0]).To(SatisfyAll( + HaveKeyWithValue("message", "could not list user shares"), + HaveKeyWithValue("error", errorcode.New(errorcode.GeneralException, "error listing shares").Error()), + HaveKeyWithValue("errorCode", "generalException"), + HaveKeyWithValue("request-id", "request-42"), + HaveKeyWithValue("userID", "user-42"), + )) + }) + + DescribeTable("logs the identity backend error when a share grantee lookup fails", + func(setup func(identityClient *cs3mocks.GatewayAPIClient, resourceID *provider.ResourceId, groupGrantee *provider.Grantee), listingMethod string) { + const identityBackendMessage = "ldap search failed for cn=private-group-dn-42,ou=groups" + identityClient := cs3mocks.NewGatewayAPIClient(GinkgoT()) + selector := mocks.NewSelectable[gateway.GatewayAPIClient](GinkgoT()) + selector.EXPECT().Next().Return(identityClient, nil) + resourceID := &provider.ResourceId{StorageId: "storageid", SpaceId: "spaceid", OpaqueId: "opaqueid"} + groupGrantee := &provider.Grantee{ + Type: provider.GranteeType_GRANTEE_TYPE_GROUP, + Id: &provider.Grantee_GroupId{GroupId: &grouppb.GroupId{OpaqueId: "groupid"}}, + } + setup(identityClient, resourceID, groupGrantee) + identityClient.On("Stat", mock.Anything, mock.Anything).Return(&provider.StatResponse{ + Status: status.NewOK(ctx), + Info: &provider.ResourceInfo{Id: resourceID, Type: provider.ResourceType_RESOURCE_TYPE_CONTAINER}, + }, nil) + identityClient.On("GetGroup", mock.Anything, mock.Anything).Return(&grouppb.GetGroupResponse{ + Status: status.NewInternal(ctx, identityBackendMessage), + }, nil) + s := newLoggedService(selector) + + s.GetSharedByMe(rr, httptest.NewRequest(http.MethodGet, "/graph/v1.0/me/drives/sharedByMe", nil)) + + // the rendered error is unchanged + Expect(rr.Code).To(Equal(http.StatusInternalServerError)) + Expect(odataError().Error.Code).To(Equal("generalException")) + Expect(odataError().Error.Message).To(Equal( + errorcode.New(errorcode.GeneralException, + errorcode.New(errorcode.GeneralException, identityBackendMessage).Error()).Error())) + // the shares were listed and the group grantee was looked up, listing stops before the public shares + identityClient.AssertCalled(GinkgoT(), listingMethod, mock.Anything, mock.Anything) + identityClient.AssertCalled(GinkgoT(), "GetGroup", mock.Anything, mock.MatchedBy(func(req *grouppb.GetGroupRequest) bool { + return req.GetGroupId().GetOpaqueId() == "groupid" + })) + identityClient.AssertNotCalled(GinkgoT(), "ListPublicShares", mock.Anything, mock.Anything) + + entries := logEntries(logBuf) + errorEntries := entriesAtLevel(entries, "error") + Expect(errorEntries).To(HaveLen(1)) + // the handler logs the error text, which carries the identity backend message + Expect(errorEntries[0]).To(HaveKeyWithValue("error", ContainSubstring(identityBackendMessage))) + for _, payloadKey := range []string{"shares", "share", "group", "res", "response"} { + Expect(entries).ToNot(ContainElement(HaveKey(payloadKey))) + } + }, + Entry("user share listing", + func(identityClient *cs3mocks.GatewayAPIClient, resourceID *provider.ResourceId, groupGrantee *provider.Grantee) { + identityClient.On("ListShares", mock.Anything, mock.Anything).Return(&collaboration.ListSharesResponse{ + Status: status.NewOK(ctx), + Shares: []*collaboration.Share{{ + Id: &collaboration.ShareId{OpaqueId: "groupshareid"}, + ResourceId: resourceID, + Grantee: groupGrantee, + Permissions: &collaboration.SharePermissions{Permissions: editorResourcePermissions}, + }}, + }, nil) + }, + "ListShares", + ), + Entry("ocm share listing", + func(identityClient *cs3mocks.GatewayAPIClient, resourceID *provider.ResourceId, groupGrantee *provider.Grantee) { + cfg.IncludeOCMSharees = true + identityClient.On("ListShares", mock.Anything, mock.Anything).Return(&collaboration.ListSharesResponse{ + Status: status.NewOK(ctx), + Shares: []*collaboration.Share{}, + }, nil) + identityClient.On("ListOCMShares", mock.Anything, mock.Anything).Return(&ocm.ListOCMSharesResponse{ + Status: status.NewOK(ctx), + Shares: []*ocm.Share{{ + Id: &ocm.ShareId{OpaqueId: "ocmgroupshareid"}, + ResourceId: resourceID, + Grantee: groupGrantee, + }}, + }, nil) + }, + "ListOCMShares", + ), + ) + + It("logs an ocm share listing failure once as error", func() { + cfg.IncludeOCMSharees = true + emptyListSharesMock() + gatewayClient.On("ListOCMShares", mock.Anything, mock.Anything).Return( + &ocm.ListOCMSharesResponse{Status: status.NewInternal(ctx, "error listing ocm shares")}, + nil, + ) + s := newLoggedService(gatewaySelector) + + s.GetSharedByMe(rr, httptest.NewRequest(http.MethodGet, "/graph/v1.0/me/drives/sharedByMe", nil)) + + Expect(rr.Code).To(Equal(http.StatusInternalServerError)) + Expect(odataError().Error.Code).To(Equal("generalException")) + Expect(odataError().Error.Message).To(Equal("error listing ocm shares")) + gatewayClient.AssertNotCalled(GinkgoT(), "ListPublicShares", mock.Anything, mock.Anything) + entries := errorEntries() + Expect(entries).To(HaveLen(1)) + Expect(entries[0]).To(SatisfyAll( + HaveKeyWithValue("message", "could not list ocm shares"), + HaveKeyWithValue("error", errorcode.New(errorcode.GeneralException, "error listing ocm shares").Error()), + )) + }) + + It("logs a gateway selection failure while listing ocm shares as error in the helper and the operation", func() { + cfg.IncludeOCMSharees = true + emptyListSharesMock() + // the user share listing gets a client, the ocm share listing does not + selector := mocks.NewSelectable[gateway.GatewayAPIClient](GinkgoT()) + selector.EXPECT().Next().Return(gatewayClient, nil).Times(1) + selector.EXPECT().Next().Return(nil, errors.New("no gateway available")).Times(1) + s := newLoggedService(selector) + + s.GetSharedByMe(rr, httptest.NewRequest(http.MethodGet, "/graph/v1.0/me/drives/sharedByMe", nil)) + + Expect(rr.Code).To(Equal(http.StatusInternalServerError)) + Expect(odataError().Error.Code).To(Equal("generalException")) + Expect(odataError().Error.Message).To(Equal("no gateway available")) + gatewayClient.AssertCalled(GinkgoT(), "ListShares", mock.Anything, mock.Anything) + gatewayClient.AssertNotCalled(GinkgoT(), "ListOCMShares", mock.Anything, mock.Anything) + // the helper and the handler both log the reason, the handler with the error code + Expect(errorEntries()).To(ConsistOf( + gatewayHelperEntry("could not select next gateway client", "no gateway available"), + SatisfyAll( + HaveKeyWithValue("message", "could not list ocm shares"), + HaveKeyWithValue("error", errorcode.New(errorcode.GeneralException, "no gateway available").Error()), + ), + )) + }) + + It("logs a public share listing failure once as error", func() { + emptyListSharesMock() + gatewayClient.On("ListPublicShares", mock.Anything, mock.Anything).Return( + &link.ListPublicSharesResponse{Status: status.NewInternal(ctx, "listing failed for /Users/alice/Private/salary-2026.ods")}, + nil, + ) + s := newLoggedService(gatewaySelector) + + s.GetSharedByMe(rr, httptest.NewRequest(http.MethodGet, "/graph/v1.0/me/drives/sharedByMe", nil)) + + Expect(rr.Code).To(Equal(http.StatusInternalServerError)) + Expect(odataError().Error.Code).To(Equal("generalException")) + // the response is unchanged + Expect(odataError().Error.Message).To(Equal("listing failed for /Users/alice/Private/salary-2026.ods")) + gatewayClient.AssertCalled(GinkgoT(), "ListShares", mock.Anything, mock.Anything) + entries := errorEntries() + Expect(entries).To(HaveLen(1)) + Expect(entries[0]).To(SatisfyAll( + HaveKeyWithValue("message", "could not list public shares"), + HaveKeyWithValue("errorCode", "generalException"), + HaveKeyWithValue("error", errorcode.New(errorcode.GeneralException, "listing failed for /Users/alice/Private/salary-2026.ods").Error()), + )) + }) + + It("logs a gateway selection failure while listing public shares as error in the helper and the operation", func() { + emptyListSharesMock() + // the user share listing gets a client, the public share listing does not + selector := mocks.NewSelectable[gateway.GatewayAPIClient](GinkgoT()) + selector.EXPECT().Next().Return(gatewayClient, nil).Times(1) + selector.EXPECT().Next().Return(nil, errors.New("no gateway available")).Times(1) + s := newLoggedService(selector) + + s.GetSharedByMe(rr, httptest.NewRequest(http.MethodGet, "/graph/v1.0/me/drives/sharedByMe", nil)) + + Expect(rr.Code).To(Equal(http.StatusInternalServerError)) + Expect(odataError().Error.Code).To(Equal("generalException")) + Expect(odataError().Error.Message).To(Equal("no gateway available")) + gatewayClient.AssertCalled(GinkgoT(), "ListShares", mock.Anything, mock.Anything) + gatewayClient.AssertNotCalled(GinkgoT(), "ListPublicShares", mock.Anything, mock.Anything) + // the helper and the handler both log the reason, the handler with the error code + Expect(errorEntries()).To(ConsistOf( + gatewayHelperEntry("could not select next gateway client", "no gateway available"), + SatisfyAll( + HaveKeyWithValue("message", "could not list public shares"), + HaveKeyWithValue("error", errorcode.New(errorcode.GeneralException, "no gateway available").Error()), + ), + )) + }) + }) + Describe("GetSharedByMe", func() { It("handles a failing ListShares", func() { emptyListPublicSharesMock() diff --git a/services/graph/pkg/service/v0/users.go b/services/graph/pkg/service/v0/users.go index 5575db07b3..e66dfc2e63 100644 --- a/services/graph/pkg/service/v0/users.go +++ b/services/graph/pkg/service/v0/users.go @@ -42,7 +42,6 @@ import ( // GetMe implements the Service interface. func (g Graph) GetMe(w http.ResponseWriter, r *http.Request) { logger := g.logger.SubloggerWithRequestID(r.Context()) - logger.Debug().Msg("calling get user in /me") sanitizedPath := strings.TrimPrefix(r.URL.Path, "/graph/v1.0/") odataReq, err := godata.ParseRequest(r.Context(), sanitizedPath, r.URL.Query()) @@ -66,22 +65,23 @@ func (g Graph) GetMe(w http.ResponseWriter, r *http.Request) { return } - var me *libregraph.User - // We can just return the user from context unless we need to expand the group memberships - if !slices.Contains(exp, "memberOf") { - me = identity.CreateUserModelFromCS3(u) - } else { - var err error - logger.Debug().Msg("calling get user on backend") - me, err = g.identityBackend.GetUser(r.Context(), u.GetId().GetOpaqueId(), odataReq) - if err != nil { - logger.Debug().Err(err).Interface("user", u).Msg("could not get user from backend") - errorcode.RenderError(w, r, err) - return - } - if me.MemberOf == nil { - me.MemberOf = []libregraph.Group{} - } + // The user is always read from the identity backend: the CS3 user of the request + // context doesn't know the identities the user signed in with, and a model built + // from it would report the internal user ID as identities[].issuerAssignedId + // instead of the subject assigned by the identity provider. The group memberships + // are only looked up when $expand=memberOf asks for them. + me, err := g.identityBackend.GetUser(r.Context(), u.GetId().GetOpaqueId(), odataReq) + if err != nil { + // a user the backend doesn't know is logged at debug level, a failing backend as error + errorEvent(&logger, err).Str(_logKeyUserID, u.GetId().GetOpaqueId()).Msg("could not get user from backend") + errorcode.RenderError(w, r, err) + return + } + // An expanded relation without entries is returned as an empty array rather than + // left out, so that clients that asked for it can rely on the attribute being there. + // The JSON encoding leaves out a nil slice, but keeps an empty one. + if slices.Contains(exp, "memberOf") && me.MemberOf == nil { + me.MemberOf = []libregraph.Group{} } // expand appRoleAssignments if requested diff --git a/services/graph/pkg/service/v0/users_test.go b/services/graph/pkg/service/v0/users_test.go index 55aac117db..42fa7ff5ea 100644 --- a/services/graph/pkg/service/v0/users_test.go +++ b/services/graph/pkg/service/v0/users_test.go @@ -40,6 +40,7 @@ import ( "github.com/opencloud-eu/opencloud/services/graph/mocks" "github.com/opencloud-eu/opencloud/services/graph/pkg/config" "github.com/opencloud-eu/opencloud/services/graph/pkg/config/defaults" + "github.com/opencloud-eu/opencloud/services/graph/pkg/errorcode" identitymocks "github.com/opencloud-eu/opencloud/services/graph/pkg/identity/mocks" service "github.com/opencloud-eu/opencloud/services/graph/pkg/service/v0" ) @@ -131,6 +132,14 @@ var _ = Describe("Users", func() { }) It("gets the information", func() { + user := &libregraph.User{ + Id: libregraph.PtrString("user"), + Identities: []libregraph.ObjectIdentity{{ + Issuer: libregraph.PtrString("https://idp.example.org"), + IssuerAssignedId: libregraph.PtrString("subject-of-the-idp"), + }}, + } + identityBackend.On("GetUser", mock.Anything, "user", mock.Anything).Return(user, nil) valueService.On("GetValueByUniqueIdentifiers", mock.Anything, mock.Anything, mock.Anything). Return(&settings.GetValueResponse{ Value: &settingsmsg.ValueWithIdentifier{ @@ -155,6 +164,32 @@ var _ = Describe("Users", func() { svc.GetMe(rr, r) Expect(rr.Code).To(Equal(http.StatusOK)) + + data, err := io.ReadAll(rr.Body) + Expect(err).ToNot(HaveOccurred()) + + responseUser := &libregraph.User{} + err = json.Unmarshal(data, &responseUser) + Expect(err).ToNot(HaveOccurred()) + + // the identities come from the identity backend, not from the user ID + Expect(responseUser.GetIdentities()).To(HaveLen(1)) + Expect(responseUser.GetIdentities()[0].GetIssuer()).To(Equal("https://idp.example.org")) + Expect(responseUser.GetIdentities()[0].GetIssuerAssignedId()).To(Equal("subject-of-the-idp")) + // without $expand=memberOf, the group memberships are left out + Expect(responseUser.HasMemberOf()).To(BeFalse()) + }) + + It("renders the error of the identity backend", func() { + identityBackend.On("GetUser", mock.Anything, "user", mock.Anything). + Return(nil, errorcode.New(errorcode.ItemNotFound, "user not found")) + + r := httptest.NewRequest(http.MethodGet, "/graph/v1.0/me", nil) + r = r.WithContext(revactx.ContextSetUser(ctx, currentUser)) + svc.GetMe(rr, r) + + Expect(rr.Code).To(Equal(http.StatusNotFound)) + valueService.AssertNotCalled(GinkgoT(), "GetValueByUniqueIdentifiers", mock.Anything, mock.Anything, mock.Anything) }) It("expands the memberOf", func() { @@ -209,6 +244,7 @@ var _ = Describe("Users", func() { RoleId: "some-appRole-ID", }, } + identityBackend.On("GetUser", mock.Anything, "user", mock.Anything).Return(&libregraph.User{Id: libregraph.PtrString("user")}, nil) roleService.On("ListRoleAssignments", mock.Anything, mock.Anything, mock.Anything).Return(&settings.ListRoleAssignmentsResponse{Assignments: assignments}, nil) valueService.On("GetValueByUniqueIdentifiers", mock.Anything, mock.Anything, mock.Anything). Return(&settings.GetValueResponse{ diff --git a/services/ocm/pkg/revaconfig/config.go b/services/ocm/pkg/revaconfig/config.go index 090145dbb9..765d162989 100644 --- a/services/ocm/pkg/revaconfig/config.go +++ b/services/ocm/pkg/revaconfig/config.go @@ -3,6 +3,7 @@ package revaconfig import ( "math" "net/url" + "path/filepath" "github.com/opencloud-eu/opencloud/pkg/log" "github.com/opencloud-eu/opencloud/services/ocm/pkg/config" @@ -94,8 +95,9 @@ func OCMConfigFromStruct(cfg *config.Config, logger log.Logger) map[string]any { "expose_recipient_display_name": cfg.OCMD.ExposeRecipientDisplayName, }, "dataprovider": map[string]any{ - "prefix": "data", - "driver": "ocmreceived", + "prefix": "data", + "driver": "ocmreceived", + "upload_directory": filepath.Join(cfg.OCMStorageProvider.StorageRoot, "uploads"), "drivers": map[string]any{ "ocmreceived": map[string]any{ "insecure": cfg.OCMStorageProvider.Insecure, @@ -175,7 +177,8 @@ func OCMConfigFromStruct(cfg *config.Config, logger log.Logger) map[string]any { }, }, "storageprovider": map[string]any{ - "driver": "ocmreceived", + "driver": "ocmreceived", + "upload_directory": filepath.Join(cfg.OCMStorageProvider.StorageRoot, "uploads"), "drivers": map[string]any{ "ocmreceived": map[string]any{ "insecure": cfg.OCMStorageProvider.Insecure, diff --git a/services/postprocessing/pkg/postprocessing/postprocessing.go b/services/postprocessing/pkg/postprocessing/postprocessing.go index b3f7a5735a..f3f05f6d6a 100644 --- a/services/postprocessing/pkg/postprocessing/postprocessing.go +++ b/services/postprocessing/pkg/postprocessing/postprocessing.go @@ -130,6 +130,7 @@ func (pp *Postprocessing) finished(outcome events.PostprocessingOutcome) events. UploadID: pp.ID, ExecutingUser: pp.User, Filename: pp.Filename, + ResourceID: pp.ResourceID, Outcome: outcome, ImpersonatingUser: pp.ImpersonatingUser, } diff --git a/services/storage-users/README.md b/services/storage-users/README.md index 4774170029..a7194a707c 100644 --- a/services/storage-users/README.md +++ b/services/storage-users/README.md @@ -95,6 +95,7 @@ OPTIONS: --processing filter sessions by processing status (default: unset) --expired filter sessions by expired status (default: unset) --has-virus filter sessions by virus scan result (default: unset) + --orphaned filter sessions by whether their node metadata is unreadable (default: unset) --json output as json (default: false) --restart send restart event for all listed sessions (default: false) --resume send resume event for all listed sessions (default: false) @@ -149,6 +150,23 @@ opencloud storage-users uploads sessions --expired=true --clean opencloud storage-users uploads sessions --processing=false --has-virus=false --resume ``` +Uploads whose node metadata can no longer be read are orphaned: they can never finish +postprocessing, because the destination of the upload cannot be resolved. Such uploads stay +in processing state indefinitely and keep consuming the quota of their space. Use the +`--orphaned` filter to list them, and `--clean` to remove them and release the quota. + +```bash +# lists all orphaned upload sessions +opencloud storage-users uploads sessions --orphaned=true + +# removes them and releases the quota they consume +opencloud storage-users uploads sessions --orphaned=true --clean +``` + +Note: `--orphaned` reads the node metadata of every upload session, so it is slower than the +other filters. Cleaning an orphaned session deletes the uploaded bytes, which are the only +copy as long as postprocessing has not finished. Run the command without `--clean` first. + #### Delete Stale Nodes command diff --git a/services/storage-users/pkg/command/uploads.go b/services/storage-users/pkg/command/uploads.go index f412390a0a..42ec9c0064 100644 --- a/services/storage-users/pkg/command/uploads.go +++ b/services/storage-users/pkg/command/uploads.go @@ -20,6 +20,7 @@ import ( userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" "github.com/opencloud-eu/opencloud/pkg/config/configlog" + olog "github.com/opencloud-eu/opencloud/pkg/log" opencloudstorage "github.com/opencloud-eu/opencloud/pkg/storage" "github.com/opencloud-eu/opencloud/services/storage-users/pkg/config" "github.com/opencloud-eu/opencloud/services/storage-users/pkg/config/parser" @@ -31,6 +32,7 @@ import ( "github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/lookup" "github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/metadata/prefixes" "github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/node" + "github.com/opencloud-eu/reva/v2/pkg/upload" "github.com/opencloud-eu/reva/v2/pkg/utils" ) @@ -94,10 +96,12 @@ func ListUploadSessions(cfg *config.Config) *cobra.Command { // We need to init the posix driver with 'scanfs' disabled posixDrivers := revaconfig.Posix(cfg, false, false) // Disable async file uploads: this command only lists sessions and publishes - // events, but with async uploads enabled the driver would join the "dcfs" - // JetStream queue group. Events routed to this short-lived CLI member are - // auto-acked by the nats client and lost when the process exits, so the - // clean/restart/resume events published below would never reach the daemon. + // events, but with async uploads enabled the driver would join the + // "dcfs-revisions" JetStream queue group. Events routed to this short-lived + // CLI member are auto-acked by the nats client and lost when the process + // exits, so the daemon would miss them. The coordinator built below does not + // subscribe to postprocessing events, so the clean/restart/resume events + // published below reach the daemon. posixDrivers["asyncfileuploads"] = false drivers["posix"] = posixDrivers // Also posix refuses to start without an events stream @@ -108,15 +112,21 @@ func ListUploadSessions(cfg *config.Config) *cobra.Command { } } - fs, err := f(drivers[driver].(map[string]any), fsStream, nil) + driverConf, ok := drivers[driver].(map[string]any) + if !ok { + fmt.Fprintf(os.Stderr, "No configuration found for filesystem driver '%s'\n", cfg.Driver) + os.Exit(1) + } + fs, err := f(driverConf, fsStream, nil) if err != nil { fmt.Fprintf(os.Stderr, "Failed to initialize filesystem driver '%s'\n", cfg.Driver) return err } - managingFS, ok := fs.(storage.UploadSessionLister) - if !ok { - fmt.Fprintf(os.Stderr, "'%s' storage does not support listing upload sessions\n", cfg.Driver) + logger := olog.Configure(cfg.Service.Name, cfg.Commons, cfg.LogLevel) + coord, err := upload.NewCoordinatorFromConfig("", driverConf, fs, nil, &logger.Logger, false) + if err != nil { + fmt.Fprintf(os.Stderr, "Failed to initialize the upload coordinator: %v\n", err) os.Exit(1) } @@ -135,7 +145,7 @@ func ListUploadSessions(cfg *config.Config) *cobra.Command { } filter := buildFilter(cmd) - uploads, err := managingFS.ListUploadSessions(cmd.Context(), filter) + uploads, err := coord.ListUploadSessions(cmd.Context(), filter) if err != nil { return err } @@ -240,6 +250,7 @@ func ListUploadSessions(cfg *config.Config) *cobra.Command { listUploadSessionsCmd.Flags().Bool("processing", false, "filter sessions by processing status") listUploadSessionsCmd.Flags().Bool("expired", false, "filter sessions by expired status") listUploadSessionsCmd.Flags().Bool("has-virus", false, "filter sessions by virus scan result") + listUploadSessionsCmd.Flags().Bool("orphaned", false, "filter sessions by whether their node metadata is unreadable. Such sessions can never finish processing and can be removed with --clean") listUploadSessionsCmd.Flags().Bool("json", false, "output as json") listUploadSessionsCmd.Flags().Bool("restart", false, "send restart event for all listed sessions. Only one of resume/restart/clean can be set.") listUploadSessionsCmd.Flags().Bool("resume", false, "send resume event for all listed sessions. Only one of resume/restart/clean can be set.") @@ -261,6 +272,10 @@ func buildFilter(cmd *cobra.Command) storage.UploadSessionFilter { infectedValue, _ := cmd.Flags().GetBool("has-virus") filter.HasVirus = &infectedValue } + if cmd.Flag("orphaned").Changed { + orphanedValue, _ := cmd.Flags().GetBool("orphaned") + filter.Orphaned = &orphanedValue + } if cmd.Flag("id").Changed { idValue, _ := cmd.Flags().GetString("id") if idValue != "" { @@ -319,6 +334,24 @@ func buildInfo(filter storage.UploadSessionFilter) string { } } + if filter.Orphaned != nil { + if b.Len() != 0 { + b.WriteString(", ") + } + if !*filter.Orphaned { + if b.Len() == 0 { + b.WriteString("Not ") + } else { + b.WriteString("not ") + } + } + if b.Len() == 0 { + b.WriteString("Orphaned") + } else { + b.WriteString("orphaned") + } + } + if b.Len() == 0 { b.WriteString("Session") } else { diff --git a/services/storage-users/pkg/command/uploads_test.go b/services/storage-users/pkg/command/uploads_test.go index e65d2f920e..eb78db28d2 100644 --- a/services/storage-users/pkg/command/uploads_test.go +++ b/services/storage-users/pkg/command/uploads_test.go @@ -69,6 +69,26 @@ func TestBuildInfo(t *testing.T) { filter: storage.UploadSessionFilter{Processing: boolPtr(true), Expired: boolPtr(false), HasVirus: boolPtr(true), ID: strPtr("123")}, expectedInfo: "Processing, not expired, virusinfected session with id '123':", }, + { + alias: "orphaned", + filter: storage.UploadSessionFilter{Orphaned: boolPtr(true)}, + expectedInfo: "Orphaned sessions:", + }, + { + alias: "not orphaned", + filter: storage.UploadSessionFilter{Orphaned: boolPtr(false)}, + expectedInfo: "Not orphaned sessions:", + }, + { + alias: "processing and orphaned", + filter: storage.UploadSessionFilter{Processing: boolPtr(true), Orphaned: boolPtr(true)}, + expectedInfo: "Processing, orphaned sessions:", + }, + { + alias: "expired, not virus infected and orphaned", + filter: storage.UploadSessionFilter{Expired: boolPtr(true), HasVirus: boolPtr(false), Orphaned: boolPtr(true)}, + expectedInfo: "Expired, not virusinfected, orphaned sessions:", + }, } for _, tc := range testCases { diff --git a/services/storage-users/pkg/revaconfig/config.go b/services/storage-users/pkg/revaconfig/config.go index ddb852559f..2fbbe60295 100644 --- a/services/storage-users/pkg/revaconfig/config.go +++ b/services/storage-users/pkg/revaconfig/config.go @@ -82,6 +82,7 @@ func StorageUsersConfigFromStruct(cfg *config.Config) map[string]any { "prefix": cfg.HTTP.Prefix, "driver": storage.EffectiveDriver(cfg.Driver), "drivers": DataProviderDrivers(cfg), + "mount_id": cfg.MountID, "nats_address": cfg.Events.Addr, "nats_clusterID": cfg.Events.ClusterID, "nats_tls_insecure": cfg.Events.TLSInsecure, diff --git a/services/storage-users/pkg/revaconfig/drivers.go b/services/storage-users/pkg/revaconfig/drivers.go index 99b53564cd..24c4f1ef46 100644 --- a/services/storage-users/pkg/revaconfig/drivers.go +++ b/services/storage-users/pkg/revaconfig/drivers.go @@ -87,6 +87,7 @@ func Local(cfg *config.Config) map[string]any { // Posix is the config mapping for the Posix storage driver func Posix(cfg *config.Config, enableFSScan, enableFSWatch bool) map[string]any { return map[string]any{ + "mount_id": cfg.MountID, "root": cfg.Drivers.Posix.Root, "personalspacepath_template": cfg.Drivers.Posix.PersonalSpacePathTemplate, "personalspacealias_template": cfg.Drivers.Posix.PersonalSpaceAliasTemplate, @@ -183,6 +184,7 @@ func OwnCloudSQL(cfg *config.Config) map[string]any { // Decomposed is the config mapping for the Decomposed storage driver func Decomposed(cfg *config.Config) map[string]any { return map[string]any{ + "mount_id": cfg.MountID, "metadata_backend": "messagepack", "metadata_prefix": cfg.Drivers.Decomposed.MetadataPrefix, "propagator": cfg.Drivers.Decomposed.Propagator, @@ -243,6 +245,7 @@ func Decomposed(cfg *config.Config) map[string]any { // DecomposedsNoEvents is the config mapping for the Decomposed storage driver emitting no events func DecomposedNoEvents(cfg *config.Config) map[string]any { return map[string]any{ + "mount_id": cfg.MountID, "metadata_backend": "messagepack", "metadata_prefix": cfg.Drivers.Decomposed.MetadataPrefix, "propagator": cfg.Drivers.Decomposed.Propagator, @@ -296,6 +299,7 @@ func DecomposedNoEvents(cfg *config.Config) map[string]any { // DecomposedS3 is the config mapping for the decomposeds3 storage driver func DecomposedS3(cfg *config.Config) map[string]any { return map[string]any{ + "mount_id": cfg.MountID, "metadata_backend": "messagepack", "metadata_prefix": cfg.Drivers.DecomposedS3.MetadataPrefix, "propagator": cfg.Drivers.DecomposedS3.Propagator, @@ -366,6 +370,7 @@ func DecomposedS3(cfg *config.Config) map[string]any { // DecomposedS3NoEvents is the config mapping for the decomposeds3 storage driver emitting no events func DecomposedS3NoEvents(cfg *config.Config) map[string]any { return map[string]any{ + "mount_id": cfg.MountID, "metadata_backend": "messagepack", "metadata_prefix": cfg.Drivers.DecomposedS3.MetadataPrefix, "propagator": cfg.Drivers.DecomposedS3.Propagator, diff --git a/tests/acceptance/TestHelpers/GraphHelper.php b/tests/acceptance/TestHelpers/GraphHelper.php index acee0c4ac0..052dcf699d 100644 --- a/tests/acceptance/TestHelpers/GraphHelper.php +++ b/tests/acceptance/TestHelpers/GraphHelper.php @@ -2183,6 +2183,35 @@ class GraphHelper { ); } + /** + * @param string $baseUrl + * @param string $xRequestId + * @param string $user + * @param string $password + * @param string $spaceId + * @param string $permissionId + * + * @return ResponseInterface + * @throws GuzzleException + */ + public static function getDrivePermission( + string $baseUrl, + string $xRequestId, + string $user, + string $password, + string $spaceId, + string $permissionId + ): ResponseInterface { + $url = self::getBetaFullUrl($baseUrl, "drives/$spaceId/root/permissions/$permissionId"); + return HttpRequestHelper::get( + $url, + $xRequestId, + $user, + $password, + self::getRequestHeaders() + ); + } + /** * @param string $baseUrl * @param string $xRequestId diff --git a/tests/acceptance/bootstrap/SharingNgContext.php b/tests/acceptance/bootstrap/SharingNgContext.php index 9479ae42a8..eb446050d1 100644 --- a/tests/acceptance/bootstrap/SharingNgContext.php +++ b/tests/acceptance/bootstrap/SharingNgContext.php @@ -1724,6 +1724,27 @@ class SharingNgContext implements Context { $this->featureContext->setResponse($this->getDrivePermissionsList($user, $space)); } + /** + * @param string $user + * @param string $space + * + * @return void + * @throws GuzzleException + */ + #[When('user :user gets the last link permission of space :space using root endpoint of the Graph API')] + public function userGetsTheLastLinkPermissionOfSpaceUsingRootEndpointOfTheGraphApi(string $user, string $space): void { + $this->featureContext->setResponse( + GraphHelper::getDrivePermission( + $this->featureContext->getBaseUrl(), + $this->featureContext->getStepLineRef(), + $user, + $this->featureContext->getPasswordForUser($user), + ($this->spacesContext->getSpaceByName($user, $space))["id"], + $this->featureContext->shareNgGetLastCreatedLinkShareID() + ) + ); + } + /** * * @param string $user diff --git a/tests/acceptance/bootstrap/SpacesContext.php b/tests/acceptance/bootstrap/SpacesContext.php index 1d422b2f0c..3af2560fbe 100644 --- a/tests/acceptance/bootstrap/SpacesContext.php +++ b/tests/acceptance/bootstrap/SpacesContext.php @@ -805,6 +805,30 @@ class SpacesContext implements Context { ); } + /** + * @param string $user + * @param string $spaceName + * @param string $spaceType + * @param string $spaceId + * + * @return void + * + * @throws GuzzleException + * @throws Exception + */ + #[When('/^user "([^"]*)" (?:creates|tries to create) a space "([^"]*)" of type "([^"]*)" with id "([^"]*)" using the Graph API$/')] + public function theUserCreatesASpaceWithIdUsingTheGraphApi( + string $user, + string $spaceName, + string $spaceType, + string $spaceId + ): void { + $space = ["name" => $spaceName, "driveType" => $spaceType, "id" => $spaceId]; + $this->featureContext->setResponse( + $this->createSpace($user, $space) + ); + } + /** * Remember the available Spaces * @@ -1636,6 +1660,30 @@ class SpacesContext implements Context { ); } + /** + * Like updateSpaceName, but the new name is written with JSON escape sequences, + * e.g. "\u200b" for a zero-width space. Characters such as invisible or unusual + * spaces can't be told apart from ordinary spaces, or can't be seen at all, when + * written directly into a feature file. + * + * @param string $user + * @param string $spaceName + * @param string $escapedNewName + * + * @return void + * @throws GuzzleException + * @throws JsonException + */ + #[When('/^user "([^"]*)" (?:changes|tries to change) the name of the "([^"]*)" space to the escaped name "([^"]*)"$/')] + public function updateSpaceNameEscaped( + string $user, + string $spaceName, + string $escapedNewName + ): void { + $newName = json_decode('"' . $escapedNewName . '"', false, 512, JSON_THROW_ON_ERROR); + $this->updateSpaceName($user, $spaceName, $newName); + } + /** * * @param string $user diff --git a/tests/acceptance/features/apiOcm/share.feature b/tests/acceptance/features/apiOcm/share.feature index 3fb2acfd22..dc034839b1 100755 --- a/tests/acceptance/features/apiOcm/share.feature +++ b/tests/acceptance/features/apiOcm/share.feature @@ -1136,7 +1136,7 @@ Feature: an user shares resources using ScienceMesh application | resource | textfile.txt | And using server "REMOTE" When user "Brian" updates the content of federated share "textfile.txt" with "this is a new content" using the WebDAV API - Then the HTTP status code should be "500" + Then the HTTP status code should be "403" And using server "LOCAL" And the content of file "textfile.txt" for user "Alice" should be "ocm test" diff --git a/tests/acceptance/features/apiSharingNg1/listPermissions.feature b/tests/acceptance/features/apiSharingNg1/listPermissions.feature index 3ab389e37a..59a425ef6e 100644 --- a/tests/acceptance/features/apiSharingNg1/listPermissions.feature +++ b/tests/acceptance/features/apiSharingNg1/listPermissions.feature @@ -2926,3 +2926,60 @@ Feature: List a sharing permissions } } """ + + + Scenario: user gets a single link permission of a project space using root endpoint + Given using spaces DAV path + And the administrator has assigned the role "Space Admin" to user "Alice" using the Graph API + And user "Alice" has created a space "new-space" with the default quota using the Graph API + And user "Alice" has created the following space link share: + | space | new-space | + | permissionsRole | view | + | password | %public% | + When user "Alice" gets the last link permission of space "new-space" using root endpoint of the Graph API + Then the HTTP status code should be "200" + And the JSON data of the response should match + """ + { + "type": "object", + "required": ["createdDateTime", "hasPassword", "id", "link"], + "properties": { + "createdDateTime": { + "format": "date-time" + }, + "hasPassword": { + "const": true + }, + "id": { + "pattern": "^[a-zA-Z]{15}$" + }, + "link": { + "type": "object", + "required": [ + "@libre.graph.displayName", + "@libre.graph.quickLink", + "preventsDownload", + "type", + "webUrl" + ], + "properties": { + "@libre.graph.displayName": { + "const": "" + }, + "@libre.graph.quickLink": { + "const": false + }, + "preventsDownload": { + "const": false + }, + "type": { + "const": "view" + }, + "webUrl": { + "pattern": "^%base_url%/s/[a-zA-Z]{15}$" + } + } + } + } + } + """ diff --git a/tests/acceptance/features/apiSharingNg1/sharedByMe.feature b/tests/acceptance/features/apiSharingNg1/sharedByMe.feature index 1223b03c23..782cd63ebf 100644 --- a/tests/acceptance/features/apiSharingNg1/sharedByMe.feature +++ b/tests/acceptance/features/apiSharingNg1/sharedByMe.feature @@ -3378,7 +3378,7 @@ Feature: resources shared by user } """ - @issue-8355 + Scenario: sharer lists the link share of a project space Given using spaces DAV path And the administrator has assigned the role "Space Admin" to user "Alice" using the Graph API @@ -3413,7 +3413,7 @@ Feature: resources shared by user ], "properties": { "name": { - "const": "." + "const": "NewSpace" }, "root": { "const": {} diff --git a/tests/acceptance/features/apiSpaces/changeSpaces.feature b/tests/acceptance/features/apiSpaces/changeSpaces.feature index 3a1a62384c..438c27c1ff 100644 --- a/tests/acceptance/features/apiSpaces/changeSpaces.feature +++ b/tests/acceptance/features/apiSpaces/changeSpaces.feature @@ -58,6 +58,41 @@ Feature: Change data of space | Bob | + Scenario: user with space manager role can't change the name of a space to an empty name via the Graph API + When user "Alice" tries to change the name of the "Project Jupiter" space to "" + Then the HTTP status code should be "400" + And the user "Alice" should have a space called "Project Jupiter" + + + Scenario: user with space manager role can't change the name of a space to a name of only spaces via the Graph API + When user "Alice" tries to change the name of the "Project Jupiter" space to " " + Then the HTTP status code should be "400" + And the user "Alice" should have a space called "Project Jupiter" + + + Scenario: user with space manager role can't change the name of a space to a name of only invisible or unusual spaces via the Graph API + # \u00a0 no-break space, \u202f narrow no-break space + When user "Alice" tries to change the name of the "Project Jupiter" space to the escaped name "\u00a0\u202f" + Then the HTTP status code should be "400" + # \u2003 em space, \u2009 thin space, \u3000 ideographic space + When user "Alice" tries to change the name of the "Project Jupiter" space to the escaped name "\u2003\u2009\u3000" + Then the HTTP status code should be "400" + # \u200b zero-width space, \u200c zero-width non-joiner, \u200d zero-width joiner + When user "Alice" tries to change the name of the "Project Jupiter" space to the escaped name "\u200b\u200c\u200d" + Then the HTTP status code should be "400" + # \u2060 word joiner, \ufeff byte order mark, mixed with a tab and ordinary spaces + When user "Alice" tries to change the name of the "Project Jupiter" space to the escaped name " \u2060\t\ufeff " + Then the HTTP status code should be "400" + And the user "Alice" should have a space called "Project Jupiter" + + + Scenario: user with space manager role can change the name of a space to a name with invisible characters around it via the Graph API + # \u200b zero-width space, \ufeff byte order mark + When user "Alice" changes the name of the "Project Jupiter" space to the escaped name "\u200bProject Saturn\ufeff" + Then the HTTP status code should be "200" + And the user "Alice" should have a space called "Project Saturn" + + Scenario: user with space manager role can change the description(subtitle) of a space via the Graph API When user "Alice" changes the description of the "Project Jupiter" space to "The Death Star is a fictional mobile space station" Then the HTTP status code should be "200" diff --git a/tests/acceptance/features/apiSpaces/createSpace.feature b/tests/acceptance/features/apiSpaces/createSpace.feature index c463560a31..348cae4a11 100644 --- a/tests/acceptance/features/apiSpaces/createSpace.feature +++ b/tests/acceptance/features/apiSpaces/createSpace.feature @@ -153,3 +153,44 @@ Feature: create space | user-role | | Admin | | Space Admin | + + + Scenario: space admin creates a project space with a client-supplied id via the Graph API + Given the administrator has assigned the role "Space Admin" to user "Alice" using the Graph API + When user "Alice" creates a space "Project Mars" of type "project" with id "4e3b1a52-8f0d-4c6e-9a71-2d5f6b8c9e10" using the Graph API + Then the HTTP status code should be "201" + And the JSON response should contain space called "Project Mars" and match + """ + { + "type": "object", + "required": ["id"], + "properties": { + "id": { + "type": "string", + "pattern": "\\$4e3b1a52-8f0d-4c6e-9a71-2d5f6b8c9e10$" + } + } + } + """ + When user "Alice" looks up the single space "Project Mars" via the Graph API by using its id + Then the HTTP status code should be "200" + And the JSON response should contain space called "Project Mars" and match + """ + { + "type": "object", + "required": ["id", "name"], + "properties": { + "id": { + "type": "string", + "pattern": "\\$4e3b1a52-8f0d-4c6e-9a71-2d5f6b8c9e10$" + }, + "name": { + "type": "string", + "enum": ["Project Mars"] + } + } + } + """ + When user "Alice" tries to create a space "Project Venus" of type "project" with id "4e3b1a52-8f0d-4c6e-9a71-2d5f6b8c9e10" using the Graph API + Then the HTTP status code should be "409" + And the user "Alice" should not have a space called "Project Venus" diff --git a/vendor/github.com/opencloud-eu/reva/v2/internal/grpc/interceptors/eventsmiddleware/conversion.go b/vendor/github.com/opencloud-eu/reva/v2/internal/grpc/interceptors/eventsmiddleware/conversion.go index 8f8b61fff7..6ffedfa6e6 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/internal/grpc/interceptors/eventsmiddleware/conversion.go +++ b/vendor/github.com/opencloud-eu/reva/v2/internal/grpc/interceptors/eventsmiddleware/conversion.go @@ -248,7 +248,7 @@ func FileDownloaded(r *provider.InitiateFileDownloadResponse, req *provider.Init } // FileLocked converts the response to an events -func FileLocked(r *provider.SetLockResponse, req *provider.SetLockRequest, owner *user.UserId, executant *user.User) events.FileLocked { +func FileLocked(r *provider.SetLockResponse, req *provider.SetLockRequest, spaceOwner *user.UserId, executant *user.User) events.FileLocked { return events.FileLocked{ Executant: executant.GetId(), Ref: req.Ref, @@ -258,7 +258,7 @@ func FileLocked(r *provider.SetLockResponse, req *provider.SetLockRequest, owner } // FileUnlocked converts the response to an event -func FileUnlocked(r *provider.UnlockResponse, req *provider.UnlockRequest, owner *user.UserId, executant *user.User) events.FileUnlocked { +func FileUnlocked(r *provider.UnlockResponse, req *provider.UnlockRequest, spaceOwner *user.UserId, executant *user.User) events.FileUnlocked { return events.FileUnlocked{ Executant: executant.GetId(), Ref: req.Ref, @@ -268,17 +268,37 @@ func FileUnlocked(r *provider.UnlockResponse, req *provider.UnlockRequest, owner } // ItemTrashed converts the response to an event -func ItemTrashed(r *provider.DeleteResponse, req *provider.DeleteRequest, spaceOwner *user.UserId, executant *user.User) events.ItemTrashed { - opaqueID := utils.ReadPlainFromOpaque(r.Opaque, "opaque_id") +func ItemTrashed(r *provider.DeleteResponse, req *provider.DeleteRequest, result *storage.DeleteResult, executant *user.User) events.ItemTrashed { + var spaceOwner *user.UserId + var id *provider.ResourceId + if result != nil { + spaceOwner = result.SpaceOwner + id = result.ResourceId + } + reqID := req.GetRef().GetResourceId() + if id == nil { + // drivers without a typed result: the storageprovider puts the id of + // the deleted node into the response opaque, the request may only + // carry the id of a parent and a relative path + opaqueID := utils.ReadPlainFromOpaque(r.GetOpaque(), "opaque_id") + if opaqueID == "" { + opaqueID = reqID.GetOpaqueId() + } + if reqID != nil || opaqueID != "" { + id = &provider.ResourceId{ + StorageId: reqID.GetStorageId(), + SpaceId: reqID.GetSpaceId(), + OpaqueId: opaqueID, + } + } + } else if id.GetStorageId() == "" { + id.StorageId = reqID.GetStorageId() + } return events.ItemTrashed{ - SpaceOwner: spaceOwner, - Executant: executant.GetId(), - Ref: req.Ref, - ID: &provider.ResourceId{ - StorageId: req.Ref.GetResourceId().GetStorageId(), - SpaceId: req.Ref.GetResourceId().GetSpaceId(), - OpaqueId: opaqueID, - }, + SpaceOwner: spaceOwner, + Executant: executant.GetId(), + Ref: req.Ref, + ID: id, Timestamp: utils.TSNow(), ImpersonatingUser: extractImpersonator(executant), } @@ -286,18 +306,11 @@ func ItemTrashed(r *provider.DeleteResponse, req *provider.DeleteRequest, spaceO // ItemMoved converts the response to an event func ItemMoved(r *provider.MoveResponse, req *provider.MoveRequest, result *storage.MoveResult, executant *user.User) events.ItemMoved { - var spaceOwner *user.UserId - var newRef, oldRef *provider.Reference - if result != nil { - spaceOwner = result.SpaceOwner - newRef = result.NewReference - oldRef = result.OldReference - } return events.ItemMoved{ - SpaceOwner: spaceOwner, + SpaceOwner: result.SpaceOwner, Executant: executant.GetId(), - Ref: newRef, - OldReference: oldRef, + Ref: result.NewReference, + OldReference: result.OldReference, Timestamp: utils.TSNow(), ImpersonatingUser: extractImpersonator(executant), } @@ -487,13 +500,21 @@ func SpaceDisabled(r *provider.DeleteStorageSpaceResponse, req *provider.DeleteS } // SpaceDeleted converts the response to an event -func SpaceDeleted(r *provider.DeleteStorageSpaceResponse, req *provider.DeleteStorageSpaceRequest, executant *user.User) events.SpaceDeleted { +func SpaceDeleted(r *provider.DeleteStorageSpaceResponse, req *provider.DeleteStorageSpaceRequest, result *storage.DeleteStorageSpaceResult, executant *user.User) events.SpaceDeleted { + var spaceName string var final map[string]provider.ResourcePermissions - _ = utils.ReadJSONFromOpaque(r.GetOpaque(), "grants", &final) + if result != nil { + spaceName = result.SpaceName + final = result.FinalMembers + } else { + // drivers without a typed result: fall back to the response opaque + spaceName = utils.ReadPlainFromOpaque(r.GetOpaque(), "spacename") + _ = utils.ReadJSONFromOpaque(r.GetOpaque(), "grants", &final) + } return events.SpaceDeleted{ Executant: executant.GetId(), ID: req.Id, - SpaceName: utils.ReadPlainFromOpaque(r.GetOpaque(), "spacename"), + SpaceName: spaceName, FinalMembers: final, Timestamp: time.Now(), } diff --git a/vendor/github.com/opencloud-eu/reva/v2/internal/grpc/interceptors/eventsmiddleware/events.go b/vendor/github.com/opencloud-eu/reva/v2/internal/grpc/interceptors/eventsmiddleware/events.go index 960ffccb07..36efbd33ac 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/internal/grpc/interceptors/eventsmiddleware/events.go +++ b/vendor/github.com/opencloud-eu/reva/v2/internal/grpc/interceptors/eventsmiddleware/events.go @@ -22,7 +22,6 @@ import ( "context" "fmt" - user "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" ocmcore "github.com/cs3org/go-cs3apis/cs3/ocm/core/v1beta1" rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1" collaboration "github.com/cs3org/go-cs3apis/cs3/sharing/collaboration/v1beta1" @@ -58,24 +57,22 @@ func NewUnary(m map[string]interface{}) (grpc.UnaryServerInterceptor, int, error } interceptor := func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { - // Register a channel in the context to receive the space owner id from the handler(s) further down the stack - var ownerID *user.UserId - sendOwnerChan := make(chan *user.UserId) - ctx = storagespace.ContextRegisterSendOwnerChan(ctx, sendOwnerChan) + // Register slots so the storage driver can pass data back up through + // the immutable context chain; values are read here after the handler returns. + ctx = storagespace.ContextRegisterSpaceOwnerSlot(ctx) + ctx = storagespace.ContextRegisterMoveResultSlot(ctx) + // Register a slot for typed Delete results + ctx = storagespace.ContextRegisterDeleteResultSlot(ctx) - moveSlot := &storagespace.MoveResultSlot{} - ctx = storagespace.ContextRegisterMoveResultSlot(ctx, moveSlot) + // Register a slot for typed DeleteStorageSpace results + ctx = storagespace.ContextRegisterDeleteStorageSpaceResultSlot(ctx) res, err := handler(ctx, req) if err != nil { return res, err } - // Read the space owner id from the channel - select { - case ownerID = <-sendOwnerChan: - default: - } + spaceOwnerID := storagespace.ContextGetSpaceOwner(ctx) // nil if not set by handler executant, _ := revactx.ContextGetUser(ctx) @@ -83,7 +80,9 @@ func NewUnary(m map[string]interface{}) (grpc.UnaryServerInterceptor, int, error switch v := res.(type) { case *provider.MoveResponse: if isSuccess(v) { - ev = ItemMoved(v, req.(*provider.MoveRequest), moveSlot.Result, executant) + if result := storagespace.ContextGetMoveResult(ctx); result != nil { + ev = ItemMoved(v, req.(*provider.MoveRequest), result, executant) + } } case *collaboration.CreateShareResponse: if isSuccess(v) { @@ -140,7 +139,7 @@ func NewUnary(m map[string]interface{}) (grpc.UnaryServerInterceptor, int, error } case *provider.CreateContainerResponse: if isSuccess(v) { - ev = ContainerCreated(v, req.(*provider.CreateContainerRequest), ownerID, executant) + ev = ContainerCreated(v, req.(*provider.CreateContainerRequest), spaceOwnerID, executant) } case *provider.InitiateFileDownloadResponse: if isSuccess(v) { @@ -148,7 +147,7 @@ func NewUnary(m map[string]interface{}) (grpc.UnaryServerInterceptor, int, error } case *provider.DeleteResponse: if isSuccess(v) { - ev = ItemTrashed(v, req.(*provider.DeleteRequest), ownerID, executant) + ev = ItemTrashed(v, req.(*provider.DeleteRequest), storagespace.ContextGetDeleteResult(ctx), executant) } case *provider.PurgeRecycleResponse: if isSuccess(v) { @@ -162,11 +161,11 @@ func NewUnary(m map[string]interface{}) (grpc.UnaryServerInterceptor, int, error } case *provider.RestoreRecycleItemResponse: if isSuccess(v) { - ev = ItemRestored(v, req.(*provider.RestoreRecycleItemRequest), ownerID, executant) + ev = ItemRestored(v, req.(*provider.RestoreRecycleItemRequest), spaceOwnerID, executant) } case *provider.RestoreFileVersionResponse: if isSuccess(v) { - ev = FileVersionRestored(v, req.(*provider.RestoreFileVersionRequest), ownerID, executant) + ev = FileVersionRestored(v, req.(*provider.RestoreFileVersionRequest), spaceOwnerID, executant) } case *provider.CreateStorageSpaceResponse: if isSuccess(v) && v.StorageSpace != nil { // TODO: Why are there CreateStorageSpaceResponses with nil StorageSpace? @@ -188,22 +187,22 @@ func NewUnary(m map[string]interface{}) (grpc.UnaryServerInterceptor, int, error if isSuccess(v) { r := req.(*provider.DeleteStorageSpaceRequest) if utils.ExistsInOpaque(r.Opaque, "purge") { - ev = SpaceDeleted(v, r, executant) + ev = SpaceDeleted(v, r, storagespace.ContextGetDeleteStorageSpaceResult(ctx), executant) } else { ev = SpaceDisabled(v, r, executant) } } case *provider.TouchFileResponse: if isSuccess(v) { - ev = FileTouched(v, req.(*provider.TouchFileRequest), ownerID, executant) + ev = FileTouched(v, req.(*provider.TouchFileRequest), spaceOwnerID, executant) } case *provider.SetLockResponse: if isSuccess(v) { - ev = FileLocked(v, req.(*provider.SetLockRequest), ownerID, executant) + ev = FileLocked(v, req.(*provider.SetLockRequest), spaceOwnerID, executant) } case *provider.UnlockResponse: if isSuccess(v) { - ev = FileUnlocked(v, req.(*provider.UnlockRequest), ownerID, executant) + ev = FileUnlocked(v, req.(*provider.UnlockRequest), spaceOwnerID, executant) } } diff --git a/vendor/github.com/opencloud-eu/reva/v2/internal/grpc/services/publicshareprovider/publicshareprovider.go b/vendor/github.com/opencloud-eu/reva/v2/internal/grpc/services/publicshareprovider/publicshareprovider.go index 8d8b0c6a71..88684ac3ae 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/internal/grpc/services/publicshareprovider/publicshareprovider.go +++ b/vendor/github.com/opencloud-eu/reva/v2/internal/grpc/services/publicshareprovider/publicshareprovider.go @@ -24,6 +24,7 @@ import ( "fmt" "regexp" "strconv" + "strings" "time" gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1" @@ -458,10 +459,10 @@ func (s *service) ListPublicShares(ctx context.Context, req *link.ListPublicShar user, _ := ctxpkg.ContextGetUser(ctx) shares, err := s.sm.ListPublicShares(ctx, user, req.Filters, req.GetSign()) - if err != nil { - log.Err(err).Msg("error listing shares") + if err != nil && !strings.Contains(err.Error(), errtypes.ERR_ALREADY_EXISTS) { + log.Err(err).Str("user", user.GetId().GetOpaqueId()).Msg("error listing shares") return &link.ListPublicSharesResponse{ - Status: status.NewInternal(ctx, "error listing public shares"), + Status: status.NewInternal(ctx, err.Error()), }, nil } diff --git a/vendor/github.com/opencloud-eu/reva/v2/internal/grpc/services/storageprovider/storageprovider.go b/vendor/github.com/opencloud-eu/reva/v2/internal/grpc/services/storageprovider/storageprovider.go index dbd9ca7196..7539a0a6af 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/internal/grpc/services/storageprovider/storageprovider.go +++ b/vendor/github.com/opencloud-eu/reva/v2/internal/grpc/services/storageprovider/storageprovider.go @@ -47,6 +47,7 @@ import ( "github.com/opencloud-eu/reva/v2/pkg/storage" "github.com/opencloud-eu/reva/v2/pkg/storage/fs/registry" "github.com/opencloud-eu/reva/v2/pkg/storagespace" + "github.com/opencloud-eu/reva/v2/pkg/upload" "github.com/opencloud-eu/reva/v2/pkg/utils" "github.com/pkg/errors" "github.com/rs/zerolog" @@ -71,6 +72,7 @@ type config struct { MountID string `mapstructure:"mount_id"` UploadExpiration int64 `mapstructure:"upload_expiration" docs:"0;Duration for how long uploads will be valid."` Events eventconfig `mapstructure:"events" docs:"0;Event stream configuration"` + UploadDirectory string `mapstructure:"upload_directory" docs:";Local directory for staging upload sessions. Overrides the driver's root. Required for drivers that have no local filesystem root."` } type eventconfig struct { @@ -106,6 +108,7 @@ func (c *config) init() { type Service struct { conf *config Storage storage.FS + Coordinator upload.Coordinator dataServerURL *url.URL availableXS []*provider.ResourceChecksumPriority } @@ -175,7 +178,14 @@ func New(m map[string]interface{}, ss *grpc.Server, log *zerolog.Logger) (rgrpc. c.init() - fs, err := getFS(c, log) + // One stream for both the driver and the coordinator: a second one would open a + // second nats connection for the same events. + evstream, err := estreamFromConfig(c.Events) + if err != nil { + return nil, err + } + + fs, err := getFS(c, evstream, log) if err != nil { return nil, err } @@ -202,9 +212,16 @@ func New(m map[string]interface{}, ss *grpc.Server, log *zerolog.Logger) (rgrpc. return nil, err } + // storageprovider only initiates uploads; the data path assembles chunks, so no chunking here. + coord, err := upload.NewCoordinatorFromConfig(c.UploadDirectory, c.Drivers[c.Driver], fs, evstream, log, false) + if err != nil { + return nil, fmt.Errorf("storageprovider: %w", err) + } + service := &Service{ conf: c, Storage: fs, + Coordinator: coord, dataServerURL: u, availableXS: xsTypes, } @@ -239,7 +256,13 @@ func (s *Service) SetLock(ctx context.Context, req *provider.SetLockRequest) (*p Status: status.NewPermissionDenied(ctx, nil, "no permission to lock the share"), }, nil } - err := s.Storage.SetLock(ctx, req.Ref, req.Lock) + res, err := s.Storage.SetLock(ctx, req.Ref, req.Lock) + if err != nil { + return &provider.SetLockResponse{ + Status: status.NewStatusFromErrType(ctx, "set lock", err), + }, nil + } + storagespace.ContextSetSpaceOwner(ctx, res.SpaceOwner) return &provider.SetLockResponse{ Status: status.NewStatusFromErrType(ctx, "set lock", err), @@ -279,7 +302,13 @@ func (s *Service) Unlock(ctx context.Context, req *provider.UnlockRequest) (*pro }, nil } - err := s.Storage.Unlock(ctx, req.Ref, req.Lock) + res, err := s.Storage.Unlock(ctx, req.Ref, req.Lock) + if err != nil { + return &provider.UnlockResponse{ + Status: status.NewStatusFromErrType(ctx, "unlock", err), + }, nil + } + storagespace.ContextSetSpaceOwner(ctx, res.SpaceOwner) return &provider.UnlockResponse{ Status: status.NewStatusFromErrType(ctx, "unlock", err), @@ -414,7 +443,7 @@ func (s *Service) InitiateFileUpload(ctx context.Context, req *provider.Initiate metadata["expires"] = strconv.Itoa(int(expirationTimestamp.Seconds)) } - uploadIDs, err := s.Storage.InitiateUpload(ctx, req.Ref, uploadLength, metadata) + uploadIDs, err := s.Coordinator.InitiateUpload(ctx, req.Ref, uploadLength, metadata) if err != nil { var st *rpc.Status switch err.(type) { @@ -582,6 +611,10 @@ func (s *Service) ListStorageSpaces(ctx context.Context, req *provider.ListStora }, nil } + caps := storage.FullCapabilities() + if cp, ok := s.Storage.(storage.CapabilityProvider); ok { + caps = cp.Capabilities(ctx) + } for _, sp := range spaces { if sp.GetId() == nil || sp.GetId().GetOpaqueId() == "" { log.Error().Str("service", "storageprovider").Str("driver", s.conf.Driver).Interface("space", sp).Msg("space is missing space id and root id") @@ -589,6 +622,7 @@ func (s *Service) ListStorageSpaces(ctx context.Context, req *provider.ListStora } s.addMissingStorageProviderID(sp.GetRoot(), sp.GetId()) + sp.Opaque = utils.AppendJSONToOpaque(sp.Opaque, storage.CapabilitiesOpaqueKey, caps) } return &provider.ListStorageSpacesResponse{ @@ -649,7 +683,8 @@ func (s *Service) DeleteStorageSpace(ctx context.Context, req *provider.DeleteSt }, nil } - if err := s.Storage.DeleteStorageSpace(ctx, req); err != nil { + result, err := s.Storage.DeleteStorageSpace(ctx, req) + if err != nil { var st *rpc.Status switch err.(type) { case errtypes.IsNotFound: @@ -672,6 +707,10 @@ func (s *Service) DeleteStorageSpace(ctx context.Context, req *provider.DeleteSt }, nil } + if result != nil { + storagespace.ContextSetDeleteStorageSpaceResult(ctx, result) + } + // TODO: update cs3api o := utils.AppendPlainToOpaque(nil, "spacename", spaces[0].GetName()) o.Map["grants"] = spaces[0].GetOpaque().GetMap()["grants"] @@ -691,7 +730,13 @@ func (s *Service) CreateContainer(ctx context.Context, req *provider.CreateConta } } - err := s.Storage.CreateDir(ctx, req.Ref) + res, err := s.Storage.CreateDir(ctx, req.Ref) + if err != nil { + return &provider.CreateContainerResponse{ + Status: status.NewStatusFromErrType(ctx, "create container", err), + }, nil + } + storagespace.ContextSetSpaceOwner(ctx, res.SpaceOwner) return &provider.CreateContainerResponse{ Status: status.NewStatusFromErrType(ctx, "create container", err), @@ -708,7 +753,13 @@ func (s *Service) TouchFile(ctx context.Context, req *provider.TouchFileRequest) mtime = utils.ReadPlainFromOpaque(req.Opaque, "X-OC-Mtime") } - err := s.Storage.TouchFile(ctx, req.Ref, utils.ExistsInOpaque(req.Opaque, "markprocessing"), mtime) + res, err := s.Storage.TouchFile(ctx, req.Ref, utils.ExistsInOpaque(req.Opaque, "markprocessing"), mtime) + if err != nil { + return &provider.TouchFileResponse{ + Status: status.NewStatusFromErrType(ctx, "touch file", err), + }, nil + } + storagespace.ContextSetSpaceOwner(ctx, res.SpaceOwner) return &provider.TouchFileResponse{ Status: status.NewStatusFromErrType(ctx, "touch file", err), @@ -774,7 +825,10 @@ func (s *Service) Delete(ctx context.Context, req *provider.DeleteRequest) (*pro }, nil } - err = s.Storage.Delete(ctx, req.Ref) + result, err := s.Storage.Delete(ctx, req.Ref) + if err == nil && result != nil { + storagespace.ContextSetDeleteResult(ctx, result) + } return &provider.DeleteResponse{ Status: status.NewStatusFromErrType(ctx, "delete", err), @@ -903,7 +957,13 @@ func (s *Service) ListFileVersions(ctx context.Context, req *provider.ListFileVe func (s *Service) RestoreFileVersion(ctx context.Context, req *provider.RestoreFileVersionRequest) (*provider.RestoreFileVersionResponse, error) { ctx = ctxpkg.ContextSetLockID(ctx, req.LockId) - err := s.Storage.RestoreRevision(ctx, req.Ref, req.Key) + res, err := s.Storage.RestoreRevision(ctx, req.Ref, req.Key) + if err != nil { + return &provider.RestoreFileVersionResponse{ + Status: status.NewStatusFromErrType(ctx, "restore file version", err), + }, nil + } + storagespace.ContextSetSpaceOwner(ctx, res.SpaceOwner) return &provider.RestoreFileVersionResponse{ Status: status.NewStatusFromErrType(ctx, "restore file version", err), @@ -1002,12 +1062,17 @@ func (s *Service) RestoreRecycleItem(ctx context.Context, req *provider.RestoreR // TODO(labkode): CRITICAL: fill recycle info with storage provider. key, relativePath := splitKeyAndPath(req.GetKey()) - err := s.Storage.RestoreRecycleItem(ctx, req.Ref, key, relativePath, req.RestoreRef) - - res := &provider.RestoreRecycleItemResponse{ - Status: status.NewStatusFromErrType(ctx, "restore recycle item", err), + writeRes, err := s.Storage.RestoreRecycleItem(ctx, req.Ref, key, relativePath, req.RestoreRef) + if err != nil { + return &provider.RestoreRecycleItemResponse{ + Status: status.NewStatusFromErrType(ctx, "restore recycle item", err), + }, nil } - return res, nil + storagespace.ContextSetSpaceOwner(ctx, writeRes.SpaceOwner) + + return &provider.RestoreRecycleItemResponse{ + Status: status.NewStatusFromErrType(ctx, "restore recycle item", err), + }, nil } func (s *Service) PurgeRecycle(ctx context.Context, req *provider.PurgeRecycleRequest) (*provider.PurgeRecycleResponse, error) { @@ -1330,12 +1395,7 @@ func (s *Service) addMissingStorageProviderID(resourceID *provider.ResourceId, s } } -func getFS(c *config, log *zerolog.Logger) (storage.FS, error) { - evstream, err := estreamFromConfig(c.Events) - if err != nil { - return nil, err - } - +func getFS(c *config, evstream events.Stream, log *zerolog.Logger) (storage.FS, error) { if f, ok := registry.NewFuncs[c.Driver]; ok { driverConf := c.Drivers[c.Driver] driverConf["mount_id"] = c.MountID // pass the mount id to the driver diff --git a/vendor/github.com/opencloud-eu/reva/v2/internal/grpc/services/usershareprovider/usershareprovider.go b/vendor/github.com/opencloud-eu/reva/v2/internal/grpc/services/usershareprovider/usershareprovider.go index a1d8b33185..119e7a2fb0 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/internal/grpc/services/usershareprovider/usershareprovider.go +++ b/vendor/github.com/opencloud-eu/reva/v2/internal/grpc/services/usershareprovider/usershareprovider.go @@ -53,6 +53,7 @@ import ( ) const ( + _fieldMaskPathExpiration = "expiration" _fieldMaskPathMountPoint = "mount_point" _fieldMaskPathPermissions = "permissions" _fieldMaskPathState = "state" @@ -268,6 +269,9 @@ func (s *service) CreateShare(ctx context.Context, req *collaboration.CreateShar if sRes.GetInfo().GetSpace().GetSpaceType() == _spaceTypePersonal || sRes.GetInfo().GetSpace().GetSpaceType() == _spaceTypeVirtual { return &collaboration.CreateShareResponse{Status: status.NewInvalid(ctx, "space type is not eligible for sharing")}, nil } + if HasPartialGrantPermissions(req.GetGrant().GetPermissions().GetPermissions()) { + return &collaboration.CreateShareResponse{Status: status.NewInvalid(ctx, "partial grant management permissions are not allowed on space roots")}, nil + } } // do not allow share to myself or the owner if share is for a user @@ -363,8 +367,19 @@ func HasGrantPermissions(p *provider.ResourcePermissions) bool { return p.GetAddGrant() || p.GetUpdateGrant() || p.GetRemoveGrant() || p.GetDenyGrant() } +// managerPerms is the manager bitmap a space root share needs if it carries any grant management permission +var managerPerms = conversions.NewManagerRole().CS3ResourcePermissions() + +// HasPartialGrantPermissions returns true if p carries some grant management permissions +// without being a full manager. On a space root such a share would make the grantee a +// manager the UI does not show as one. +func HasPartialGrantPermissions(p *provider.ResourcePermissions) bool { + return HasGrantPermissions(p) && !conversions.SufficientCS3Permissions(p, managerPerms) +} + // spaceRootHasRemainingManager returns true if the given resource has at least one share -// (excluding the share with excludeShareOpaqueID) that grants both AddGrant and RemoveGrant. +// (excluding the share with excludeShareOpaqueID) that grants both AddGrant and RemoveGrant +// and does not expire. func (s *service) spaceRootHasRemainingManager(ctx context.Context, resourceID *provider.ResourceId, excludeShareOpaqueID string) (bool, error) { shares, err := s.sm.ListShares(ctx, []*collaboration.Filter{ { @@ -380,13 +395,34 @@ func (s *service) spaceRootHasRemainingManager(ctx context.Context, resourceID * continue } perms := s.GetPermissions().GetPermissions() - if perms.GetAddGrant() && perms.GetRemoveGrant() { + // Expirable shares won't be computed because the space needs + // at least one permanent space manager. + if perms.GetAddGrant() && perms.GetRemoveGrant() && s.GetExpiration() == nil { return true, nil } } return false, nil } +// mayRemoveLastPermanentManager reports whether an update could leave a space without a permanent +// manager share, so the caller must verify that another one remains. That is the case when the new +// permissions strip AddGrant or RemoveGrant, or when the share keeps the manager permissions but gets +// an expiration, because expiring shares do not count as permanent managers. +func mayRemoveLastPermanentManager(currentShare *collaboration.Share, newPermissions *provider.ResourcePermissions, req *collaboration.UpdateShareRequest) bool { + if newPermissions != nil && (!newPermissions.GetAddGrant() || !newPermissions.GetRemoveGrant()) { + return true + } + permissions := newPermissions + if permissions == nil { + permissions = currentShare.GetPermissions().GetPermissions() + } + expiration := currentShare.GetExpiration() + if slices.Contains(req.GetUpdateMask().GetPaths(), _fieldMaskPathExpiration) { + expiration = req.GetShare().GetExpiration() + } + return permissions.GetAddGrant() && permissions.GetRemoveGrant() && expiration != nil +} + func (s *service) RemoveShare(ctx context.Context, req *collaboration.RemoveShareRequest) (*collaboration.RemoveShareResponse, error) { log := appctx.GetLogger(ctx) user := ctxpkg.ContextMustGetUser(ctx) @@ -597,15 +633,20 @@ func (s *service) UpdateShare(ctx context.Context, req *collaboration.UpdateShar } else { newPermissions = req.GetField().GetPermissions().GetPermissions() } + if utils.IsSpaceRoot(sRes.GetInfo()) && HasPartialGrantPermissions(newPermissions) { + return &collaboration.UpdateShareResponse{ + Status: status.NewInvalid(ctx, "partial grant management permissions are not allowed on space roots"), + }, nil + } if newPermissions != nil && !conversions.SufficientCS3Permissions(sRes.GetInfo().GetPermissionSet(), newPermissions) { return &collaboration.UpdateShareResponse{ Status: status.NewPermissionDenied(ctx, nil, "insufficient permissions to create that kind of share"), }, nil } - // For space root shares, if the new permissions would strip AddGrant or RemoveGrant from this share, - // ensure at least one other share still has both so the space retains a manager. - if utils.IsSpaceRoot(sRes.GetInfo()) && newPermissions != nil && (!newPermissions.GetAddGrant() || !newPermissions.GetRemoveGrant()) { + // For space root shares, if the update would strip AddGrant or RemoveGrant from this share or give + // a manager share an expiration, ensure at least one other permanent manager share remains. + if utils.IsSpaceRoot(sRes.GetInfo()) && mayRemoveLastPermanentManager(currentShare, newPermissions, req) { if ok, err := s.spaceRootHasRemainingManager(ctx, currentShare.GetResourceId(), currentShare.GetId().GetOpaqueId()); err != nil { return &collaboration.UpdateShareResponse{ Status: status.NewInternal(ctx, "failed to list shares for space root"), diff --git a/vendor/github.com/opencloud-eu/reva/v2/internal/http/services/dataprovider/dataprovider.go b/vendor/github.com/opencloud-eu/reva/v2/internal/http/services/dataprovider/dataprovider.go index ad7b5be561..79ca3b4750 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/internal/http/services/dataprovider/dataprovider.go +++ b/vendor/github.com/opencloud-eu/reva/v2/internal/http/services/dataprovider/dataprovider.go @@ -33,6 +33,7 @@ import ( "github.com/opencloud-eu/reva/v2/pkg/rhttp/router" "github.com/opencloud-eu/reva/v2/pkg/storage" "github.com/opencloud-eu/reva/v2/pkg/storage/fs/registry" + "github.com/opencloud-eu/reva/v2/pkg/upload" ) func init() { @@ -51,6 +52,7 @@ type config struct { NatsEnableTLS bool `mapstructure:"nats_enable_tls"` NatsUsername string `mapstructure:"nats_username"` NatsPassword string `mapstructure:"nats_password"` + UploadDirectory string `mapstructure:"upload_directory" docs:";Local directory for staging upload sessions. Overrides the driver's root. Required for drivers that have no local filesystem root."` } func (c *config) init() { @@ -104,7 +106,21 @@ func New(m map[string]interface{}, log *zerolog.Logger) (global.Service, error) return nil, err } - dataTXs, err := getDataTXs(conf, fs, evstream, log) + // the data path assembles chunks, so enable chunking + coord, err := upload.NewCoordinatorFromConfig(conf.UploadDirectory, conf.Drivers[conf.Driver], fs, evstream, log, true) + if err != nil { + return nil, fmt.Errorf("dataprovider: %w", err) + } + + // only the data path consumes postprocessing results: one consumer group gets + // one copy of each event, so a second subscriber would take half of them + if ac := upload.AsyncConfFromDriverConf(conf.Drivers[conf.Driver]); ac.Enabled { + if err := coord.StartPostprocessing(evstream, ac); err != nil { + return nil, fmt.Errorf("dataprovider: could not start postprocessing: %w", err) + } + } + + dataTXs, err := getDataTXs(conf, coord, fs, evstream, log) if err != nil { return nil, err } @@ -126,7 +142,7 @@ func getFS(c *config, stream events.Stream, log *zerolog.Logger) (storage.FS, er return nil, fmt.Errorf("driver not found: %s", c.Driver) } -func getDataTXs(c *config, fs storage.FS, publisher events.Publisher, log *zerolog.Logger) (map[string]http.Handler, error) { +func getDataTXs(c *config, coord upload.Coordinator, fs storage.FS, publisher events.Publisher, log *zerolog.Logger) (map[string]http.Handler, error) { if c.DataTXs == nil { c.DataTXs = make(map[string]map[string]interface{}) } @@ -146,7 +162,7 @@ func getDataTXs(c *config, fs storage.FS, publisher events.Publisher, log *zerol for t := range c.DataTXs { if f, ok := datatxregistry.NewFuncs[t]; ok { if tx, err := f(c.DataTXs[t], publisher, log); err == nil { - if handler, err := tx.Handler(fs); err == nil { + if handler, err := tx.Handler(coord, fs); err == nil { txs[t] = handler } } diff --git a/vendor/github.com/opencloud-eu/reva/v2/internal/http/services/owncloud/ocdav/tus.go b/vendor/github.com/opencloud-eu/reva/v2/internal/http/services/owncloud/ocdav/tus.go index fc567f627e..329dc4b52b 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/internal/http/services/owncloud/ocdav/tus.go +++ b/vendor/github.com/opencloud-eu/reva/v2/internal/http/services/owncloud/ocdav/tus.go @@ -337,7 +337,8 @@ func (s *svc) handleTusPost(ctx context.Context, w http.ResponseWriter, r *http. sReq.Ref.Path = uReq.Ref.GetPath() sReq.Ref.ResourceId = nil } else { - if resid, err := storagespace.ParseID(httpRes.Header.Get(net.HeaderOCFileID)); err == nil { + // new files have no node id yet; keep the path-based ref instead + if resid, err := storagespace.ParseID(httpRes.Header.Get(net.HeaderOCFileID)); err == nil && resid.GetOpaqueId() != "" { sReq.Ref = &provider.Reference{ ResourceId: &resid, } diff --git a/vendor/github.com/opencloud-eu/reva/v2/internal/http/services/owncloud/ocs/handlers/cloud/capabilities/capabilities.go b/vendor/github.com/opencloud-eu/reva/v2/internal/http/services/owncloud/ocs/handlers/cloud/capabilities/capabilities.go index 350fed869c..e746485cb7 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/internal/http/services/owncloud/ocs/handlers/cloud/capabilities/capabilities.go +++ b/vendor/github.com/opencloud-eu/reva/v2/internal/http/services/owncloud/ocs/handlers/cloud/capabilities/capabilities.go @@ -31,6 +31,7 @@ type Handler struct { c ocs.CapabilitiesData defaultUploadProtocol string userAgentChunkingMap map[string]string + gatewayAddr string } // Init initializes this and any contained handlers @@ -38,6 +39,7 @@ func (h *Handler) Init(c *config.Config) { h.c = c.Capabilities h.defaultUploadProtocol = c.DefaultUploadProtocol h.userAgentChunkingMap = c.UserAgentChunkingMap + h.gatewayAddr = c.GatewaySvc // capabilities if h.c.Capabilities == nil { @@ -120,8 +122,9 @@ func (h *Handler) Init(c *config.Config) { if h.c.Capabilities.Dav == nil { h.c.Capabilities.Dav = &ocs.CapabilitiesDav{} } - if h.c.Capabilities.Dav.Trashbin == "" { - h.c.Capabilities.Dav.Trashbin = "1.0" + // Trashbin is deprecated for clients, but we keep announcing it until they read the providers section. + if h.c.Capabilities.Dav.Trashbin == "" { //nolint:staticcheck // SA1019: still announced for older clients + h.c.Capabilities.Dav.Trashbin = "1.0" //nolint:staticcheck // SA1019: still announced for older clients } if h.c.Capabilities.Dav.Reports == nil { h.c.Capabilities.Dav.Reports = []string{} @@ -241,5 +244,10 @@ func (h *Handler) Init(c *config.Config) { // Handler renders the capabilities func (h *Handler) GetCapabilities(w http.ResponseWriter, r *http.Request) { c := h.getCapabilitiesForUserAgent(r.UserAgent()) + if providers := h.resolveProviders(r.Context()); len(providers) > 0 && c.Capabilities != nil { + caps := *c.Capabilities + caps.Providers = providers + c.Capabilities = &caps + } response.WriteOCSSuccess(w, r, c) } diff --git a/vendor/github.com/opencloud-eu/reva/v2/internal/http/services/owncloud/ocs/handlers/cloud/capabilities/providers.go b/vendor/github.com/opencloud-eu/reva/v2/internal/http/services/owncloud/ocs/handlers/cloud/capabilities/providers.go new file mode 100644 index 0000000000..f0ce769095 --- /dev/null +++ b/vendor/github.com/opencloud-eu/reva/v2/internal/http/services/owncloud/ocs/handlers/cloud/capabilities/providers.go @@ -0,0 +1,53 @@ +package capabilities + +import ( + "context" + + rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1" + provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" + + "github.com/opencloud-eu/reva/v2/pkg/appctx" + "github.com/opencloud-eu/reva/v2/pkg/owncloud/ocs" + "github.com/opencloud-eu/reva/v2/pkg/rgrpc/todo/pool" + "github.com/opencloud-eu/reva/v2/pkg/storage" + "github.com/opencloud-eu/reva/v2/pkg/utils" +) + +// resolveProviders builds the per-provider capability map from the spaces visible +// to the current user, keyed by provider ID. Returns nil on no user context or an +// unreachable gateway, so the response omits the section rather than failing. +func (h *Handler) resolveProviders(ctx context.Context) map[string]*ocs.ProviderCapabilities { + log := appctx.GetLogger(ctx) + + gc, err := pool.GetGatewayServiceClient(h.gatewayAddr) + if err != nil { + log.Error().Err(err).Msg("capabilities: error getting gateway client") + return nil + } + + res, err := gc.ListStorageSpaces(ctx, &provider.ListStorageSpacesRequest{}) + if err != nil { + log.Error().Err(err).Msg("capabilities: error listing storage spaces") + return nil + } + if res.GetStatus().GetCode() != rpc.Code_CODE_OK { + return nil + } + + providers := map[string]*ocs.ProviderCapabilities{} + for _, sp := range res.GetStorageSpaces() { + id := sp.GetRoot().GetStorageId() + if id == "" { + continue + } + if _, done := providers[id]; done { + continue + } + var caps storage.Capabilities + if err := utils.ReadJSONFromOpaque(sp.GetOpaque(), storage.CapabilitiesOpaqueKey, &caps); err != nil { + continue + } + providers[id] = ocs.NewProviderCapabilities(caps) + } + return providers +} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/errtypes/errtypes.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/errtypes/errtypes.go index 5ef7e995bf..ddf8807c60 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/errtypes/errtypes.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/errtypes/errtypes.go @@ -99,7 +99,11 @@ func (e PreconditionFailed) IsPreconditionFailed() {} // AlreadyExists is the error to use when a resource something is not found. type AlreadyExists string -func (e AlreadyExists) Error() string { return "error: already exists: " + string(e) } +// ERR_ALREADY_EXISTS is the prefix of every AlreadyExists error message, for callers +// that only see the message (e.g. a status message passed through grpc). +const ERR_ALREADY_EXISTS = "error: already exists:" + +func (e AlreadyExists) Error() string { return ERR_ALREADY_EXISTS + " " + string(e) } // IsAlreadyExists implements the IsAlreadyExists interface. func (e AlreadyExists) IsAlreadyExists() {} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/events/postprocessing.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/events/postprocessing.go index e443f82947..3769cb7a8b 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/events/postprocessing.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/events/postprocessing.go @@ -103,6 +103,7 @@ type PostprocessingStepFinished struct { UploadID string ExecutingUser *user.User Filename string + ResourceID *provider.ResourceId FinishedStep Postprocessingstep // name of the step Result interface{} // result information see VirusscanResult for example @@ -145,6 +146,7 @@ type VirusscanResult struct { type PostprocessingFinished struct { UploadID string Filename string + ResourceID *provider.ResourceId SpaceOwner *user.UserId ExecutingUser *user.User Result map[Postprocessingstep]interface{} // it is a map[step]Event diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/events/stream/nats.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/events/stream/nats.go index 4fbaa5cfee..4758d84bf5 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/events/stream/nats.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/events/stream/nats.go @@ -18,6 +18,11 @@ import ( "github.com/opencloud-eu/reva/v2/pkg/logger" ) +const ( + mainQueueName = "main-queue" + mainQueueMaxAge = 7 * 24 * time.Hour +) + // NatsConfig is the configuration needed for a NATS event stream type NatsConfig struct { Endpoint string `mapstructure:"address"` // Endpoint of the nats server @@ -87,21 +92,43 @@ func NatsFromConfig(connName string, disableDurability bool, cfg NatsConfig) (ev if err != nil { return nil, err } - streamCfg := jetstream.StreamConfig{ - Name: "main-queue", - MaxAge: 7 * 24 * time.Hour, - } - _, err = jsConn.CreateStream(ctx, streamCfg) - if err != nil { - // If the stream already exists, update its configuration - if err == jetstream.ErrStreamNameAlreadyInUse { - _, _ = jsConn.UpdateStream(ctx, streamCfg) - } + if err := ensureMainQueueMaxAge(ctx, jsConn); err != nil { + logger.New().Warn().Err(err).Str("stream", mainQueueName).Msg("could not apply max age to the main queue") } return s, nil } +// ensureMainQueueMaxAge creates the main queue with a MaxAge or sets the MaxAge +// on an existing main queue that doesn't have one yet. All other settings of an +// existing stream, like the number of replicas, are left alone because a stream +// update replaces the whole config and would reset them to their defaults. +func ensureMainQueueMaxAge(ctx context.Context, js jetstream.JetStream) error { + stream, err := js.Stream(ctx, mainQueueName) + if errors.Is(err, jetstream.ErrStreamNotFound) { + _, err = js.CreateStream(ctx, jetstream.StreamConfig{ + Name: mainQueueName, + MaxAge: mainQueueMaxAge, + }) + if !errors.Is(err, jetstream.ErrStreamNameAlreadyInUse) { + return err + } + // another service created it in the meantime + stream, err = js.Stream(ctx, mainQueueName) + } + if err != nil { + return err + } + + cfg := stream.CachedInfo().Config + if cfg.MaxAge != 0 { + return nil + } + cfg.MaxAge = mainQueueMaxAge + _, err = js.UpdateStream(ctx, cfg) + return err +} + // nats returns a nats streaming client // retries exponentially to connect to a nats server func Nats(opts ...natsjs.Option) (events.Stream, error) { diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/ocm/storage/received/ocm.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/ocm/storage/received/ocm.go index 4936a46008..8ed06bb22f 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/ocm/storage/received/ocm.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/ocm/storage/received/ocm.go @@ -40,6 +40,7 @@ import ( "github.com/rs/zerolog" "github.com/studio-b12/gowebdav" + ctxpkg "github.com/opencloud-eu/reva/v2/pkg/ctx" "github.com/opencloud-eu/reva/v2/pkg/errtypes" "github.com/opencloud-eu/reva/v2/pkg/events" "github.com/opencloud-eu/reva/v2/pkg/mime" @@ -209,28 +210,37 @@ func (d *driver) webdavClient(ctx context.Context, forUser *userpb.UserId, ref * return c, share, rel, nil } -func (d *driver) CreateDir(ctx context.Context, ref *provider.Reference) error { +func (d *driver) CreateDir(ctx context.Context, ref *provider.Reference) (*storage.CreateDirResult, error) { client, _, rel, err := d.webdavClient(ctx, nil, ref) if err != nil { - return err + return nil, err } - return client.MkdirAll(rel, 0) + if err := client.MkdirAll(rel, 0); err != nil { + return nil, err + } + return &storage.CreateDirResult{}, nil } -func (d *driver) Delete(ctx context.Context, ref *provider.Reference) error { - client, _, rel, err := d.webdavClient(ctx, nil, ref) +func (d *driver) Delete(ctx context.Context, ref *provider.Reference) (*storage.DeleteResult, error) { + client, _, rel, err := d.serviceWebdavClient(ctx, ref) if err != nil { - return err + return nil, err } - return client.RemoveAll(rel) + if err := client.RemoveAll(rel); err != nil { + return nil, err + } + return &storage.DeleteResult{}, nil } -func (d *driver) TouchFile(ctx context.Context, ref *provider.Reference, markprocessing bool, mtime string) error { - client, _, rel, err := d.webdavClient(ctx, nil, ref) +func (d *driver) TouchFile(ctx context.Context, ref *provider.Reference, markprocessing bool, mtime string) (*storage.TouchFileResult, error) { + client, _, rel, err := d.serviceWebdavClient(ctx, ref) if err != nil { - return err + return nil, err } - return client.Write(rel, []byte{}, 0) + if err := client.Write(rel, []byte{}, 0); err != nil { + return nil, err + } + return &storage.TouchFileResult{}, nil } func (d *driver) Move(ctx context.Context, oldRef, newRef *provider.Reference) (*storage.MoveResult, error) { @@ -327,7 +337,19 @@ func extractChecksum(props gowebdav.Props) *provider.ResourceChecksum { } func (d *driver) GetMD(ctx context.Context, ref *provider.Reference, _ []string, _ []string) (*provider.ResourceInfo, error) { - client, share, rel, err := d.webdavClient(ctx, nil, ref) + var ( + client *gowebdav.Client + share *ocmpb.ReceivedShare + rel string + err error + ) + if token, ok := ctxpkg.ContextGetToken(ctx); ok && token != "" { + client, share, rel, err = d.webdavClient(ctx, nil, ref) + } else { + // the upload coordinator stats an upload it finishes with the context of the + // upload's executant, whose request, and with it the token, is gone by then + client, share, rel, err = d.serviceWebdavClient(ctx, ref) + } if err != nil { return nil, err } @@ -418,16 +440,16 @@ func (d *driver) DownloadRevision(ctx context.Context, ref *provider.Reference, return nil, nil, errtypes.NotSupported("operation not supported") } -func (d *driver) RestoreRevision(ctx context.Context, ref *provider.Reference, key string) error { - return errtypes.NotSupported("operation not supported") +func (d *driver) RestoreRevision(ctx context.Context, ref *provider.Reference, key string) (*storage.RestoreRevisionResult, error) { + return nil, errtypes.NotSupported("operation not supported") } func (d *driver) ListRecycle(ctx context.Context, ref *provider.Reference, key, relativePath string) ([]*provider.RecycleItem, error) { return nil, errtypes.NotSupported("operation not supported") } -func (d *driver) RestoreRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string, restoreRef *provider.Reference) error { - return errtypes.NotSupported("operation not supported") +func (d *driver) RestoreRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string, restoreRef *provider.Reference) (*storage.RestoreRecycleItemResult, error) { + return nil, errtypes.NotSupported("operation not supported") } func (d *driver) PurgeRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string) error { @@ -475,13 +497,16 @@ func (d *driver) UnsetArbitraryMetadata(ctx context.Context, ref *provider.Refer } // SetLock sets a lock on a file -func (d *driver) SetLock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) error { +func (d *driver) SetLock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) (*storage.SetLockResult, error) { client, _, rel, err := d.webdavClient(ctx, nil, ref) if err != nil { - return err + return nil, err } - return client.Lock(rel, lock.GetLockId()) + if err := client.Lock(rel, lock.GetLockId()); err != nil { + return nil, err + } + return &storage.SetLockResult{}, nil } func (d *driver) GetLock(ctx context.Context, ref *provider.Reference) (*provider.Lock, error) { @@ -494,6 +519,10 @@ func (d *driver) GetLock(ctx context.Context, ref *provider.Reference) (*provide if err != nil { return nil, err } + // gowebdav formats a missing lockdiscovery property as "" + if token == "" || token == "" { + return nil, errtypes.NotFound("no lock found") + } return &provider.Lock{LockId: token, Type: provider.LockType_LOCK_TYPE_EXCL}, nil } @@ -508,13 +537,16 @@ func (d *driver) RefreshLock(ctx context.Context, ref *provider.Reference, lock } // Unlock removes a lock from a file -func (d *driver) Unlock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) error { +func (d *driver) Unlock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) (*storage.UnlockResult, error) { client, _, rel, err := d.webdavClient(ctx, nil, ref) if err != nil { - return err + return nil, err } - return client.Unlock(rel, lock.GetLockId()) + if err := client.Unlock(rel, lock.GetLockId()); err != nil { + return nil, err + } + return &storage.UnlockResult{}, nil } func (d *driver) ListStorageSpaces(ctx context.Context, filters []*provider.ListStorageSpacesRequest_Filter, _ bool) ([]*provider.StorageSpace, error) { @@ -606,8 +638,8 @@ func (d *driver) UpdateStorageSpace(ctx context.Context, req *provider.UpdateSto return nil, errtypes.NotSupported("operation not supported") } -func (d *driver) DeleteStorageSpace(ctx context.Context, req *provider.DeleteStorageSpaceRequest) error { - return errtypes.NotSupported("operation not supported") +func (d *driver) DeleteStorageSpace(ctx context.Context, req *provider.DeleteStorageSpaceRequest) (*storage.DeleteStorageSpaceResult, error) { + return nil, errtypes.NotSupported("operation not supported") } func (d *driver) AddLabel(ctx context.Context, ref *provider.Reference, userID *userpb.UserId, label string) error { @@ -617,3 +649,11 @@ func (d *driver) AddLabel(ctx context.Context, ref *provider.Reference, userID * func (d *driver) RemoveLabel(ctx context.Context, ref *provider.Reference, userID *userpb.UserId, label string) error { return errtypes.NotSupported("RemoveLabel not implemented") } + +func (d *driver) PrepareUpload(_ context.Context, _ *provider.Reference, _ string, info storage.UploadInfo) (*storage.PrepareUploadResult, error) { + return &storage.PrepareUploadResult{VersionCreated: info.NodeExisted}, nil +} + +func (d *driver) RollbackUpload(_ context.Context, _ *provider.Reference, _ string, _ storage.RollbackInfo) error { + return nil +} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/ocm/storage/received/upload.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/ocm/storage/received/upload.go index 1331c9e6e3..5753a66a5d 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/ocm/storage/received/upload.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/ocm/storage/received/upload.go @@ -20,399 +20,57 @@ package ocm import ( "context" - "crypto/md5" - "crypto/sha1" - "encoding/hex" - "encoding/json" - "errors" - "fmt" - "hash" - "hash/adler32" - "io" "net/http" - "os" - "path/filepath" - "strings" - "github.com/google/uuid" - tusd "github.com/tus/tusd/v2/pkg/handler" + "github.com/studio-b12/gowebdav" - userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" + ocmpb "github.com/cs3org/go-cs3apis/cs3/sharing/ocm/v1beta1" provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" - "github.com/opencloud-eu/reva/v2/pkg/appctx" ctxpkg "github.com/opencloud-eu/reva/v2/pkg/ctx" "github.com/opencloud-eu/reva/v2/pkg/errtypes" "github.com/opencloud-eu/reva/v2/pkg/storage" "github.com/opencloud-eu/reva/v2/pkg/utils" ) -var defaultFilePerm = os.FileMode(0664) - -func (d *driver) ListUploadSessions(ctx context.Context, filter storage.UploadSessionFilter) ([]storage.UploadSession, error) { - return []storage.UploadSession{}, nil -} -func (d *driver) InitiateUpload(ctx context.Context, ref *provider.Reference, uploadLength int64, metadata map[string]string) (map[string]string, error) { - shareID, rel := shareInfoFromReference(ref) - p := getPathFromShareIDAndRelPath(shareID, rel) - - info := tusd.FileInfo{ - MetaData: tusd.MetaData{ - "filename": filepath.Base(p), - "dir": filepath.Dir(p), - }, - Size: uploadLength, - } - - upload, err := d.NewUpload(ctx, info) - if err != nil { - return nil, err - } - - info, _ = upload.GetInfo(ctx) - - return map[string]string{ - "simple": info.ID, - "tus": info.ID, - }, nil -} - +// MarkProcessing is a no-op: the file lives on the remote instance, so there is no +// local node to flag while postprocessing runs. func (d *driver) MarkProcessing(ctx context.Context, ref *provider.Reference, processing bool, sessionID string) error { - return errtypes.NotSupported("op not supported") + return nil } -func (d *driver) CommitUpload(_ context.Context, _ *provider.Reference, _ string, _ storage.UploadSource) error { - return errtypes.NotSupported("op not supported") -} - -func (d *driver) Upload(ctx context.Context, req storage.UploadRequest, _ storage.UploadFinishedFunc) (*provider.ResourceInfo, error) { - shareID, _ := shareInfoFromReference(req.Ref) - u, err := d.GetUpload(ctx, shareID.OpaqueId) +// CommitUpload streams the staged bytes to the remote instance. +func (d *driver) CommitUpload(ctx context.Context, ref *provider.Reference, sessionID string, source storage.UploadSource) error { + client, _, rel, err := d.serviceWebdavClient(ctx, ref) if err != nil { - return &provider.ResourceInfo{}, err + return err } - info, err := u.GetInfo(ctx) - if err != nil { - return &provider.ResourceInfo{}, err - } - - defer cleanup(&upload{Info: info}) - - client, _, rel, err := d.webdavClient(ctx, nil, &provider.Reference{ - Path: filepath.Join(info.MetaData["dir"], info.MetaData["filename"]), - }) - if err != nil { - return &provider.ResourceInfo{}, err - } client.SetInterceptor(func(method string, rq *http.Request) { // Set the content length on the request struct directly instead of the header. // The content-length header gets reset by the golang http library before - // sendind out the request, resulting in chunked encoding to be used which + // sending out the request, resulting in chunked encoding to be used which // breaks the quota checks in ocdav. if method == "PUT" { - rq.ContentLength = req.Length + rq.ContentLength = source.Length } }) - locktoken, _ := ctxpkg.ContextGetLockID(ctx) - return &provider.ResourceInfo{}, client.WriteStream(rel, req.Body, 0, locktoken) + // the coordinator owns source.Body and closes it after this returns + lockToken, _ := ctxpkg.ContextGetLockID(ctx) + return client.WriteStream(rel, source.Body, 0, lockToken) } -// UseIn tells the tus upload middleware which extensions it supports. -func (d *driver) UseIn(composer *tusd.StoreComposer) { - composer.UseCore(d) - composer.UseTerminater(d) - composer.UseConcater(d) - composer.UseLengthDeferrer(d) -} - -// AsTerminatableUpload returns a TerminatableUpload -// To implement the termination extension as specified in https://tus.io/protocols/resumable-upload.html#termination -// the storage needs to implement AsTerminatableUpload -func (d *driver) AsTerminatableUpload(up tusd.Upload) tusd.TerminatableUpload { - return up.(*upload) -} - -// AsLengthDeclarableUpload returns a LengthDeclarableUpload -// To implement the creation-defer-length extension as specified in https://tus.io/protocols/resumable-upload.html#creation -// the storage needs to implement AsLengthDeclarableUpload -func (d *driver) AsLengthDeclarableUpload(up tusd.Upload) tusd.LengthDeclarableUpload { - return up.(*upload) -} - -// AsConcatableUpload returns a ConcatableUpload -// To implement the concatenation extension as specified in https://tus.io/protocols/resumable-upload.html#concatenation -// the storage needs to implement AsConcatableUpload -func (d *driver) AsConcatableUpload(up tusd.Upload) tusd.ConcatableUpload { - return up.(*upload) -} - -// To implement the core tus.io protocol as specified in https://tus.io/protocols/resumable-upload.html#core-protocol -// - the storage needs to implement NewUpload and GetUpload -// - the upload needs to implement the tusd.Upload interface: WriteChunk, GetInfo, GetReader and FinishUpload - -// NewUpload returns a new tus Upload instance -func (d *driver) NewUpload(ctx context.Context, info tusd.FileInfo) (tusd.Upload, error) { - return NewUpload(ctx, d, d.c.StorageRoot, info) -} - -// GetUpload returns the Upload for the given upload id -func (d *driver) GetUpload(ctx context.Context, id string) (tusd.Upload, error) { - return GetUpload(ctx, d, d.c.StorageRoot, id) -} -func NewUpload(ctx context.Context, d *driver, storageRoot string, info tusd.FileInfo) (tusd.Upload, error) { - if info.MetaData["filename"] == "" { - return nil, errors.New("decomposedfs: missing filename in metadata") +// serviceWebdavClient builds a webdav client without needing a request auth token: +// it authenticates as the service account and looks up the share on behalf of the +// upload's executant. +func (d *driver) serviceWebdavClient(ctx context.Context, ref *provider.Reference) (*gowebdav.Client, *ocmpb.ReceivedShare, string, error) { + serviceUserCtx, err := utils.GetServiceUserContextWithContext(context.Background(), d.gateway, d.c.ServiceAccountID, d.c.ServiceAccountSecret) + if err != nil { + return nil, nil, "", err } - if info.MetaData["dir"] == "" { - return nil, errors.New("decomposedfs: missing dir in metadata") - } - - uploadRoot := filepath.Join(storageRoot, "uploads") - info.ID = uuid.New().String() - - user, ok := ctxpkg.ContextGetUser(ctx) + executant, ok := ctxpkg.ContextGetUser(ctx) if !ok { - return nil, errors.New("no user in context") + return nil, nil, "", errtypes.BadRequest("ocm: no executant in context") } - info.MetaData["user"] = user.GetId().GetOpaqueId() - info.MetaData["idp"] = user.GetId().GetIdp() - - info.Storage = map[string]string{ - "Type": "OCM", - "Path": uploadRoot, - } - - u := &upload{ - Info: info, - Ctx: ctx, - d: d, - } - - err := os.MkdirAll(uploadRoot, 0755) - if err != nil { - return nil, err - } - - file, err := os.OpenFile(u.BinPath(), os.O_CREATE|os.O_WRONLY, defaultFilePerm) - if err != nil { - return nil, err - } - defer file.Close() - - err = u.Persist() - if err != nil { - return nil, err - } - return u, nil -} - -func GetUpload(ctx context.Context, d *driver, storageRoot string, id string) (tusd.Upload, error) { - info := tusd.FileInfo{} - data, err := os.ReadFile(filepath.Join(storageRoot, "uploads", id+".info")) - if err != nil { - return nil, err - } - err = json.Unmarshal(data, &info) - if err != nil { - return nil, err - } - upload := &upload{ - Info: info, - Ctx: ctx, - d: d, - } - return upload, nil -} - -type upload struct { - Info tusd.FileInfo - Ctx context.Context - - d *driver -} - -func (u *upload) InfoPath() string { - return filepath.Join(u.Info.Storage["Path"], u.Info.ID+".info") -} - -func (u *upload) BinPath() string { - return filepath.Join(u.Info.Storage["Path"], u.Info.ID) -} - -func (u *upload) Persist() error { - data, err := json.Marshal(u.Info) - if err != nil { - return err - } - return os.WriteFile(u.InfoPath(), data, defaultFilePerm) -} - -func (u *upload) WriteChunk(ctx context.Context, offset int64, src io.Reader) (int64, error) { - file, err := os.OpenFile(u.BinPath(), os.O_WRONLY|os.O_APPEND, defaultFilePerm) - if err != nil { - return 0, err - } - defer file.Close() - - // calculate cheksum here? needed for the TUS checksum extension. https://tus.io/protocols/resumable-upload.html#checksum - // TODO but how do we get the `Upload-Checksum`? WriteChunk() only has a context, offset and the reader ... - // It is sent with the PATCH request, well or in the POST when the creation-with-upload extension is used - // but the tus handler uses a context.Background() so we cannot really check the header and put it in the context ... - n, err := io.Copy(file, src) - - // If the HTTP PATCH request gets interrupted in the middle (e.g. because - // the user wants to pause the upload), Go's net/http returns an io.ErrUnexpectedEOF. - // However, for the ocm driver it's not important whether the stream has ended - // on purpose or accidentally. - if err != nil && err != io.ErrUnexpectedEOF { - return n, err - } - - u.Info.Offset += n - return n, u.Persist() -} - -func (u *upload) GetInfo(ctx context.Context) (tusd.FileInfo, error) { - return u.Info, nil -} - -func (u *upload) GetReader(ctx context.Context) (io.ReadCloser, error) { - return os.Open(u.BinPath()) -} - -func (u *upload) FinishUpload(ctx context.Context) error { - log := appctx.GetLogger(u.Ctx) - - // calculate the checksum of the written bytes - // they will all be written to the metadata later, so we cannot omit any of them - // TODO only calculate the checksum in sync that was requested to match, the rest could be async ... but the tests currently expect all to be present - // TODO the hashes all implement BinaryMarshaler so we could try to persist the state for resumable upload. we would neet do keep track of the copied bytes ... - sha1h := sha1.New() - md5h := md5.New() - adler32h := adler32.New() - { - f, err := os.Open(u.BinPath()) - if err != nil { - // we can continue if no oc checksum header is set - log.Info().Err(err).Str("binPath", u.BinPath()).Msg("error opening binPath") - } - defer f.Close() - - r1 := io.TeeReader(f, sha1h) - r2 := io.TeeReader(r1, md5h) - - _, err = io.Copy(adler32h, r2) - if err != nil { - log.Info().Err(err).Msg("error copying checksums") - } - } - - defer cleanup(u) - // compare if they match the sent checksum - // TODO the tus checksum extension would do this on every chunk, but I currently don't see an easy way to pass in the requested checksum. for now we do it in FinishUpload which is also called for chunked uploads - if u.Info.MetaData["checksum"] != "" { - var err error - parts := strings.SplitN(u.Info.MetaData["checksum"], " ", 2) - if len(parts) != 2 { - return errtypes.BadRequest("invalid checksum format. must be '[algorithm] [checksum]'") - } - switch parts[0] { - case "sha1": - err = u.checkHash(parts[1], sha1h) - case "md5": - err = u.checkHash(parts[1], md5h) - case "adler32": - err = u.checkHash(parts[1], adler32h) - default: - err = errtypes.BadRequest("unsupported checksum algorithm: " + parts[0]) - } - if err != nil { - return err - } - } - - // send to the remote storage via webdav - // shareID, rel := shareInfoFromReference(u.Info.MetaData["ref"]) - // p := getPathFromShareIDAndRelPath(shareID, rel) - - serviceUserCtx, err := utils.GetServiceUserContextWithContext(context.Background(), u.d.gateway, u.d.c.ServiceAccountID, u.d.c.ServiceAccountSecret) - if err != nil { - return err - } - client, _, rel, err := u.d.webdavClient(serviceUserCtx, &userpb.UserId{ - OpaqueId: u.Info.MetaData["user"], - Idp: u.Info.MetaData["idp"], - }, &provider.Reference{ - Path: filepath.Join(u.Info.MetaData["dir"], u.Info.MetaData["filename"]), - }) - if err != nil { - return err - } - - client.SetInterceptor(func(method string, rq *http.Request) { - // Set the content length on the request struct directly instead of the header. - // The content-length header gets reset by the golang http library before - // sendind out the request, resulting in chunked encoding to be used which - // breaks the quota checks in ocdav. - if method == "PUT" { - rq.ContentLength = u.Info.Size - } - }) - - f, err := os.Open(u.BinPath()) - if err != nil { - return err - } - defer f.Close() - return client.WriteStream(rel, f, 0, "") -} - -func (u *upload) Terminate(ctx context.Context) error { - cleanup(u) - return nil -} - -func (u *upload) ConcatUploads(_ context.Context, uploads []tusd.Upload) error { - file, err := os.OpenFile(u.BinPath(), os.O_WRONLY|os.O_APPEND, defaultFilePerm) - if err != nil { - return err - } - defer file.Close() - - for _, partialUpload := range uploads { - fileUpload := partialUpload.(*upload) - - src, err := os.Open(fileUpload.BinPath()) - if err != nil { - return err - } - defer src.Close() - - if _, err := io.Copy(file, src); err != nil { - return err - } - } - return nil -} - -func (u *upload) DeclareLength(ctx context.Context, length int64) error { - u.Info.Size = length - u.Info.SizeIsDeferred = false - return nil -} - -func (u *upload) checkHash(expected string, h hash.Hash) error { - if expected != hex.EncodeToString(h.Sum(nil)) { - return errtypes.ChecksumMismatch(fmt.Sprintf("invalid checksum: expected %s got %x", u.Info.MetaData["checksum"], h.Sum(nil))) - } - return nil -} - -func cleanup(u *upload) { - if u == nil { - return - } - _ = os.Remove(u.BinPath()) - _ = os.Remove(u.InfoPath()) + return d.webdavClient(serviceUserCtx, executant.GetId(), ref) } diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/owncloud/ocs/capabilities.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/owncloud/ocs/capabilities.go index 871b182b95..3e1e00177d 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/owncloud/ocs/capabilities.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/owncloud/ocs/capabilities.go @@ -20,6 +20,10 @@ package ocs import ( "encoding/xml" + "maps" + "slices" + + "github.com/opencloud-eu/reva/v2/pkg/storage" ) // ocsBool implements the xml/json Marshaler interface. The OCS API inconsistency require us to parse boolean values @@ -62,6 +66,63 @@ type Capabilities struct { Theme *CapabilitiesTheme `json:"theme,omitempty" xml:"theme,omitempty" mapstructure:"theme"` Notifications *CapabilitiesNotifications `json:"notifications,omitempty" xml:"notifications,omitempty"` Groupware *CapabilitiesGroupware `json:"groupware,omitempty" xml:"groupware,omitempty" mapstructure:"groupware"` + // Providers is the per-provider capability section, keyed by provider ID. It + // supersedes the deprecated global storage keys under Files/Dav; there is no + // fallback between them. + Providers ProviderCapabilitiesMap `json:"providers,omitempty" xml:"providers,omitempty" mapstructure:"providers"` +} + +// ProviderCapabilitiesMap is the per-provider section keyed by provider ID. +type ProviderCapabilitiesMap map[string]*ProviderCapabilities + +// MarshalXML renders the map as ......, +// ordered by id. encoding/xml cannot marshal a Go map, so XML output is produced +// explicitly; JSON uses the default map encoding. +func (m ProviderCapabilitiesMap) MarshalXML(e *xml.Encoder, start xml.StartElement) error { + if len(m) == 0 { + return nil + } + if err := e.EncodeToken(start); err != nil { + return err + } + for _, id := range slices.Sorted(maps.Keys(m)) { + el := xml.StartElement{ + Name: xml.Name{Local: "provider"}, + Attr: []xml.Attr{{Name: xml.Name{Local: "id"}, Value: id}}, + } + if err := e.EncodeElement(m[id], el); err != nil { + return err + } + } + return e.EncodeToken(start.End()) +} + +// ProviderCapabilities is the wire form of a provider's declared capabilities. +type ProviderCapabilities struct { + Upload ocsBool `json:"upload" xml:"upload"` + CreateContainer ocsBool `json:"create_container" xml:"create_container"` + Delete ocsBool `json:"delete" xml:"delete"` + Move ocsBool `json:"move" xml:"move"` + Versioning ocsBool `json:"versioning" xml:"versioning"` + Trash ocsBool `json:"trash" xml:"trash"` + Locking ocsBool `json:"locking" xml:"locking"` + Sharing ocsBool `json:"sharing" xml:"sharing"` + ArbitraryMetadata ocsBool `json:"arbitrary_metadata" xml:"arbitrary_metadata"` +} + +// NewProviderCapabilities maps a driver's declaration onto the OCS response type. +func NewProviderCapabilities(c storage.Capabilities) *ProviderCapabilities { + return &ProviderCapabilities{ + Upload: ocsBool(c.Upload), + CreateContainer: ocsBool(c.CreateContainer), + Delete: ocsBool(c.Delete), + Move: ocsBool(c.Move), + Versioning: ocsBool(c.Versioning), + Trash: ocsBool(c.Trash), + Locking: ocsBool(c.Locking), + Sharing: ocsBool(c.Sharing), + ArbitraryMetadata: ocsBool(c.ArbitraryMetadata), + } } // CapabilitiesSearch holds the search capabilities @@ -95,12 +156,13 @@ type CapabilitiesSearchPropertyExtended struct { // Spaces lets a service configure its advertised options related to Storage Spaces. type Spaces struct { - Version string `json:"version" xml:"version" mapstructure:"version"` - Enabled bool `json:"enabled" xml:"enabled" mapstructure:"enabled"` - Projects bool `json:"projects" xml:"projects" mapstructure:"projects"` - ShareJail bool `json:"share_jail" xml:"share_jail" mapstructure:"share_jail"` - MaxQuota uint64 `json:"max_quota" xml:"max_quota" mapstructure:"max_quota"` - DefaultQuota uint64 `json:"default_quota" xml:"default_quota" mapstructure:"default_quota"` + Version string `json:"version" xml:"version" mapstructure:"version"` + Enabled bool `json:"enabled" xml:"enabled" mapstructure:"enabled"` + Projects bool `json:"projects" xml:"projects" mapstructure:"projects"` + ShareJail bool `json:"share_jail" xml:"share_jail" mapstructure:"share_jail"` + MaxQuota uint64 `json:"max_quota" xml:"max_quota" mapstructure:"max_quota"` + DefaultQuota uint64 `json:"default_quota" xml:"default_quota" mapstructure:"default_quota"` + ServerManaged bool `json:"server_managed" xml:"server_managed" mapstructure:"server_managed"` } // CapabilitiesCore holds webdav config @@ -192,10 +254,13 @@ type CapabilitiesAppProvider struct { // CapabilitiesFiles TODO this is storage specific, not global. What effect do these options have on the clients? type CapabilitiesFiles struct { - PrivateLinks ocsBool `json:"privateLinks" xml:"privateLinks" mapstructure:"private_links"` - BigFileChunking ocsBool `json:"bigfilechunking" xml:"bigfilechunking"` - Undelete ocsBool `json:"undelete" xml:"undelete"` - Versioning ocsBool `json:"versioning" xml:"versioning"` + PrivateLinks ocsBool `json:"privateLinks" xml:"privateLinks" mapstructure:"private_links"` + BigFileChunking ocsBool `json:"bigfilechunking" xml:"bigfilechunking"` + // Deprecated: use capabilities.providers[].trash. + Undelete ocsBool `json:"undelete" xml:"undelete"` + // Deprecated: use capabilities.providers[].versioning. + Versioning ocsBool `json:"versioning" xml:"versioning"` + // Deprecated: use capabilities.providers[].arbitrary_metadata. Favorites ocsBool `json:"favorites" xml:"favorites"` FullTextSearch ocsBool `json:"full_text_search" xml:"full_text_search" mapstructure:"full_text_search"` Tags ocsBool `json:"tags" xml:"tags"` @@ -207,7 +272,8 @@ type CapabilitiesFiles struct { // CapabilitiesDav holds dav endpoint config type CapabilitiesDav struct { - Chunking string `json:"chunking" xml:"chunking"` + Chunking string `json:"chunking" xml:"chunking"` + // Deprecated: use capabilities.providers[].trash. Trashbin string `json:"trashbin" xml:"trashbin"` Reports []string `json:"reports" xml:"reports>element" mapstructure:"reports"` ChunkingParallelUploadDisabled bool `json:"chunkingParallelUploadDisabled" xml:"chunkingParallelUploadDisabled"` diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/rhttp/datatx/datatx.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/rhttp/datatx/datatx.go index 40246112cf..c2d53e1a43 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/rhttp/datatx/datatx.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/rhttp/datatx/datatx.go @@ -28,12 +28,15 @@ import ( provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" "github.com/opencloud-eu/reva/v2/pkg/events" "github.com/opencloud-eu/reva/v2/pkg/storage" + "github.com/opencloud-eu/reva/v2/pkg/upload" "github.com/opencloud-eu/reva/v2/pkg/utils" ) // DataTX provides an abstraction around various data transfer protocols. type DataTX interface { - Handler(fs storage.FS) (http.Handler, error) + // Handler serves the protocol's data path. Uploads go through coord, which + // owns the upload lifecycle for every driver; downloads read from driver. + Handler(coord upload.Coordinator, driver storage.FS) (http.Handler, error) } // EmitFileUploadedEvent is a helper function which publishes a FileUploaded event diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/rhttp/datatx/manager/simple/simple.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/rhttp/datatx/manager/simple/simple.go index f1dbe801f7..52c63fdabe 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/rhttp/datatx/manager/simple/simple.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/rhttp/datatx/manager/simple/simple.go @@ -40,6 +40,7 @@ import ( "github.com/opencloud-eu/reva/v2/pkg/storage" "github.com/opencloud-eu/reva/v2/pkg/storage/cache" "github.com/opencloud-eu/reva/v2/pkg/storagespace" + "github.com/opencloud-eu/reva/v2/pkg/upload" "github.com/opencloud-eu/reva/v2/pkg/utils" ) @@ -78,7 +79,7 @@ func New(m map[string]interface{}, publisher events.Publisher, log *zerolog.Logg }, nil } -func (m *manager) Handler(fs storage.FS) (http.Handler, error) { +func (m *manager) Handler(coord upload.Coordinator, driver storage.FS) (http.Handler, error) { h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { sublog := m.log.With().Str("path", r.URL.Path).Logger() r = r.WithContext(appctx.WithLogger(r.Context(), &sublog)) @@ -92,7 +93,7 @@ func (m *manager) Handler(fs storage.FS) (http.Handler, error) { metrics.DownloadsActive.Sub(1) }() } - download.GetOrHeadFile(w, r, fs, "") + download.GetOrHeadFile(w, r, driver, "") case "PUT": metrics.UploadsActive.Add(1) defer func() { @@ -114,7 +115,7 @@ func (m *manager) Handler(fs storage.FS) (http.Handler, error) { ctx = ctxpkg.ContextSetLockID(ctx, lockID) } - info, err := fs.Upload(ctx, storage.UploadRequest{ + info, err := coord.Upload(ctx, upload.Request{ Ref: ref, Body: r.Body, Length: r.ContentLength, diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/rhttp/datatx/manager/spaces/spaces.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/rhttp/datatx/manager/spaces/spaces.go index 133120a89d..50fb54eff6 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/rhttp/datatx/manager/spaces/spaces.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/rhttp/datatx/manager/spaces/spaces.go @@ -42,6 +42,7 @@ import ( "github.com/opencloud-eu/reva/v2/pkg/storage" "github.com/opencloud-eu/reva/v2/pkg/storage/cache" "github.com/opencloud-eu/reva/v2/pkg/storagespace" + "github.com/opencloud-eu/reva/v2/pkg/upload" "github.com/opencloud-eu/reva/v2/pkg/utils" ) @@ -80,7 +81,7 @@ func New(m map[string]interface{}, publisher events.Publisher, log *zerolog.Logg }, nil } -func (m *manager) Handler(fs storage.FS) (http.Handler, error) { +func (m *manager) Handler(coord upload.Coordinator, driver storage.FS) (http.Handler, error) { h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { var spaceID string spaceID, r.URL.Path = router.ShiftPath(r.URL.Path) @@ -97,7 +98,7 @@ func (m *manager) Handler(fs storage.FS) (http.Handler, error) { metrics.DownloadsActive.Sub(1) }() } - download.GetOrHeadFile(w, r, fs, spaceID) + download.GetOrHeadFile(w, r, driver, spaceID) case "PUT": metrics.UploadsActive.Add(1) defer func() { @@ -117,7 +118,7 @@ func (m *manager) Handler(fs storage.FS) (http.Handler, error) { Path: fn, } var info *provider.ResourceInfo - info, err = fs.Upload(ctx, storage.UploadRequest{ + info, err = coord.Upload(ctx, upload.Request{ Ref: ref, Body: r.Body, Length: r.ContentLength, diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/rhttp/datatx/manager/tus/tus.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/rhttp/datatx/manager/tus/tus.go index ae478a30ec..59aa291f85 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/rhttp/datatx/manager/tus/tus.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/rhttp/datatx/manager/tus/tus.go @@ -35,13 +35,13 @@ import ( "github.com/opencloud-eu/reva/v2/internal/http/services/owncloud/ocdav/net" "github.com/opencloud-eu/reva/v2/pkg/appctx" - "github.com/opencloud-eu/reva/v2/pkg/errtypes" "github.com/opencloud-eu/reva/v2/pkg/events" "github.com/opencloud-eu/reva/v2/pkg/rhttp/datatx" "github.com/opencloud-eu/reva/v2/pkg/rhttp/datatx/manager/registry" "github.com/opencloud-eu/reva/v2/pkg/rhttp/datatx/metrics" "github.com/opencloud-eu/reva/v2/pkg/storage" "github.com/opencloud-eu/reva/v2/pkg/storagespace" + "github.com/opencloud-eu/reva/v2/pkg/upload" ) func init() { @@ -89,20 +89,19 @@ func New(m map[string]interface{}, publisher events.Publisher, log *zerolog.Logg }, nil } -func (m *manager) Handler(fs storage.FS) (http.Handler, error) { - composable, ok := fs.(storage.ComposableFS) - if !ok { - return nil, errtypes.NotSupported("file system does not support the tus protocol") - } +func (m *manager) Handler(coord upload.Coordinator, fs storage.FS) (http.Handler, error) { + // such a driver creates a new file under the id minted at initiate, so that id is + // already the file's + nc, ok := fs.(storage.NodeCreator) + createsNode := ok && nc.PrepareCreatesNode() // A storage backend for tusd may consist of multiple different parts which // handle upload creation, locking, termination and so on. The composer is a - // place where all those separated pieces are joined together. In this example - // we only use the file store but you may plug in multiple. + // place where all those separated pieces are joined together. composer := tusd.NewStoreComposer() - // let the composable storage tell tus which extensions it supports - composable.UseIn(composer) + // the coordinator serves the tus protocol on behalf of every driver + coord.UseIn(composer) config := tusd.Config{ StoreComposer: composer, @@ -110,7 +109,7 @@ func (m *manager) Handler(fs storage.FS) (http.Handler, error) { Logger: slog.New(tusdLogger{log: m.log}), // Add the finalized resource's etag and permissions to the last chunk's response // (see preFinishResponseCallback). https://github.com/opencloud-eu/opencloud/issues/2409 - PreFinishResponseCallback: m.preFinishResponseCallback(fs), + PreFinishResponseCallback: m.preFinishResponseCallback(coord), } if m.conf.CorsEnabled { @@ -135,33 +134,29 @@ func (m *manager) Handler(fs storage.FS) (http.Handler, error) { return nil, err } - if usl, ok := fs.(storage.UploadSessionLister); ok { - // We can currently only send updates if the fs is decomposedfs as we read very specific keys from the storage map of the tus info - go func() { - for { - ev := <-handler.CompleteUploads - // We should be able to get the upload progress with fs.GetUploadProgress, but currently tus will erase the info files - // so we create a Progress instance here that is used to read the correct properties - ups, err := usl.ListUploadSessions(context.Background(), storage.UploadSessionFilter{ID: &ev.Upload.ID}) - if err != nil { - appctx.GetLogger(context.Background()).Error().Err(err).Str("session", ev.Upload.ID).Msg("failed to list upload session") - } else { - if len(ups) < 1 { - appctx.GetLogger(context.Background()).Error().Str("session", ev.Upload.ID).Msg("upload session not found") - continue - } - up := ups[0] - executant := up.Executant() - ref := up.Reference() - if m.publisher != nil { - if err := datatx.EmitFileUploadedEvent(up.SpaceOwner(), &executant, &ref, m.publisher); err != nil { - appctx.GetLogger(context.Background()).Error().Err(err).Msg("failed to publish FileUploaded event") - } - } + go func() { + for { + ev := <-handler.CompleteUploads + // tus erases its info files, so read the session back for the event's properties + ups, err := coord.ListUploadSessions(context.Background(), storage.UploadSessionFilter{ID: &ev.Upload.ID}) + if err != nil { + appctx.GetLogger(context.Background()).Error().Err(err).Str("session", ev.Upload.ID).Msg("failed to list upload session") + continue + } + if len(ups) < 1 { + appctx.GetLogger(context.Background()).Error().Str("session", ev.Upload.ID).Msg("upload session not found") + continue + } + up := ups[0] + executant := up.Executant() + ref := up.Reference() + if m.publisher != nil { + if err := datatx.EmitFileUploadedEvent(up.SpaceOwner(), &executant, &ref, m.publisher); err != nil { + appctx.GetLogger(context.Background()).Error().Err(err).Msg("failed to publish FileUploaded event") } } - }() - } + } + }() h := handler.Middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { sublog := m.log.With().Str("uploadid", r.URL.Path).Logger() @@ -179,7 +174,7 @@ func (m *manager) Handler(fs storage.FS) (http.Handler, error) { metrics.UploadsActive.Sub(1) }() // set etag, mtime and file id - setHeaders(fs, w, r) + setHeaders(coord, createsNode, w, r) handler.PostFile(w, r) case "HEAD": handler.HeadFile(w, r) @@ -189,7 +184,7 @@ func (m *manager) Handler(fs storage.FS) (http.Handler, error) { metrics.UploadsActive.Sub(1) }() // set etag, mtime and file id - setHeaders(fs, w, r) + setHeaders(coord, createsNode, w, r) handler.PatchFile(w, r) case "DELETE": handler.DelFile(w, r) @@ -214,16 +209,16 @@ func (m *manager) Handler(fs storage.FS) (http.Handler, error) { // the final response is written, it looks up the finalized resource and attaches its etag and // WebDAV permissions to the response headers, so clients do not need a follow-up PROPFIND after // the last chunk. It mirrors the etag and permissions the ocdav gateway already produces for the -// creation-with-upload path. The storage driver resolves the resource as the upload's executant -// (the data path's transfer token carries no user identity), so this layer does not reconstruct -// the user. It is best effort: it logs any lookup failure and still completes the upload (the +// creation-with-upload path. The upload coordinator resolves the resource as the upload's +// executant (the data path's transfer token carries no user identity), so this layer does not +// reconstruct the user. It is best effort: it logs any lookup failure and still completes the upload (the // client falls back to a PROPFIND). https://github.com/opencloud-eu/opencloud/issues/2409 -func (m *manager) preFinishResponseCallback(fs storage.FS) func(tusd.HookEvent) (tusd.HTTPResponse, error) { - resolver, ok := fs.(storage.UploadSessionResolver) +func (m *manager) preFinishResponseCallback(r any) func(tusd.HookEvent) (tusd.HTTPResponse, error) { + resolver, ok := r.(storage.UploadSessionResolver) return func(hook tusd.HookEvent) (tusd.HTTPResponse, error) { resp := tusd.HTTPResponse{Header: tusd.HTTPHeader{}} if !ok { - // the storage driver cannot resolve the upload; the client falls back to a PROPFIND + // nothing resolves the upload; the client falls back to a PROPFIND return resp, nil } @@ -246,15 +241,10 @@ func (m *manager) preFinishResponseCallback(fs storage.FS) func(tusd.HookEvent) } } -func setHeaders(fs storage.FS, w http.ResponseWriter, r *http.Request) { +func setHeaders(coord upload.Coordinator, createsNode bool, w http.ResponseWriter, r *http.Request) { ctx := r.Context() id := path.Base(r.URL.Path) - datastore, ok := fs.(tusd.DataStore) - if !ok { - appctx.GetLogger(ctx).Error().Interface("fs", fs).Msg("storage is not a tus datastore") - return - } - upload, err := datastore.GetUpload(ctx, id) + upload, err := coord.GetUpload(ctx, id) if err != nil { appctx.GetLogger(ctx).Error().Err(err).Msg("could not get upload from storage") return @@ -268,12 +258,23 @@ func setHeaders(fs storage.FS, w http.ResponseWriter, r *http.Request) { if expires != "" { w.Header().Set(net.HeaderTusUploadExpires, expires) } - resourceid := &provider.ResourceId{ + if id := fileID(info, createsNode); id != "" { + w.Header().Set(net.HeaderOCFileID, id) + } +} + +// fileID returns the id of the file an upload writes, or "" while it is not known yet: +// a new file's id is only valid once the upload commits, unless the driver creates the +// file under the id minted at initiate. +func fileID(info tusd.FileInfo, createsNode bool) string { + if info.Storage["NodeExists"] != "true" && !createsNode { + return "" + } + return storagespace.FormatResourceID(&provider.ResourceId{ StorageId: info.MetaData["providerID"], SpaceId: info.Storage["SpaceRoot"], OpaqueId: info.Storage["NodeId"], - } - w.Header().Set(net.HeaderOCFileID, storagespace.FormatResourceID(resourceid)) + }) } // tusdLogger is a logger implementation (slog) for tusd that uses zerolog. diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/rhttp/datatx/metrics/metrics.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/rhttp/datatx/metrics/metrics.go index 79441f69c3..f1875483ca 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/rhttp/datatx/metrics/metrics.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/rhttp/datatx/metrics/metrics.go @@ -44,6 +44,11 @@ var ( Name: "reva_upload_sessions_aborted", Help: "Number of upload sessions that have been aborted by postprocessing", }) + // UploadSessionsCommitFailed is the number of upload sessions whose blob commit failed after retries and were reverted + UploadSessionsCommitFailed = promauto.NewCounter(prometheus.CounterOpts{ + Name: "reva_upload_sessions_commit_failed", + Help: "Number of upload sessions whose blob commit failed after retries and were reverted", + }) // UploadSessionsDeleted is the number of upload sessions that have been deleted UploadSessionsDeleted = promauto.NewCounter(prometheus.CounterOpts{ Name: "reva_upload_sessions_deleted", diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/hello/unimplemented.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/hello/unimplemented.go index 631fb0d069..3ebed75249 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/hello/unimplemented.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/hello/unimplemented.go @@ -48,26 +48,26 @@ func (fs *hellofs) UpdateStorageSpace(ctx context.Context, req *provider.UpdateS } // DeleteStorageSpace deletes a storage space -func (fs *hellofs) DeleteStorageSpace(ctx context.Context, req *provider.DeleteStorageSpaceRequest) error { - return errtypes.NotSupported("delete storage space") +func (fs *hellofs) DeleteStorageSpace(ctx context.Context, req *provider.DeleteStorageSpaceRequest) (*storage.DeleteStorageSpaceResult, error) { + return nil, errtypes.NotSupported("delete storage space") } // CreateDir creates a resource of type container -func (fs *hellofs) CreateDir(ctx context.Context, ref *provider.Reference) error { - return errtypes.NotSupported("unimplemented") +func (fs *hellofs) CreateDir(ctx context.Context, ref *provider.Reference) (*storage.CreateDirResult, error) { + return nil, errtypes.NotSupported("unimplemented") } // TouchFile sets the mtime of a resource, creating an empty file if it does not exist // FIXME the markprocessing flag is an implementation detail of decomposedfs, remove it from the function // FIXME the mtime should either be a time.Time or a CS3 Timestamp, not a string -func (fs *hellofs) TouchFile(ctx context.Context, ref *provider.Reference, _ bool, _ string) error { - return errtypes.NotSupported("unimplemented") +func (fs *hellofs) TouchFile(ctx context.Context, ref *provider.Reference, _ bool, _ string) (*storage.TouchFileResult, error) { + return nil, errtypes.NotSupported("unimplemented") } // Delete deletes a resource. // If the storage driver supports a recycle bin it should moves it to the recycle bin -func (fs *hellofs) Delete(ctx context.Context, ref *provider.Reference) error { - return errtypes.NotSupported("unimplemented") +func (fs *hellofs) Delete(ctx context.Context, ref *provider.Reference) (*storage.DeleteResult, error) { + return nil, errtypes.NotSupported("unimplemented") } // Move changes the path of a resource @@ -75,16 +75,6 @@ func (fs *hellofs) Move(ctx context.Context, oldRef, newRef *provider.Reference) return nil, errtypes.NotSupported("unimplemented") } -// Upload creates or updates a resource of type file with a new revision -func (fs *hellofs) Upload(ctx context.Context, req storage.UploadRequest, uff storage.UploadFinishedFunc) (*provider.ResourceInfo, error) { - return nil, errtypes.NotSupported("hellofs: upload not supported") -} - -// InitiateUpload returns a list of protocols with urls that can be used to append bytes to a new upload session -func (fs *hellofs) InitiateUpload(ctx context.Context, ref *provider.Reference, uploadLength int64, metadata map[string]string) (map[string]string, error) { - return nil, errtypes.NotSupported("hellofs: initiate upload not supported") -} - // MarkProcessing toggles a processing flag on the resource. func (fs *hellofs) MarkProcessing(ctx context.Context, ref *provider.Reference, processing bool, sessionID string) error { return errtypes.NotSupported("hellofs: mark processing not supported") @@ -95,6 +85,14 @@ func (fs *hellofs) CommitUpload(_ context.Context, _ *provider.Reference, _ stri return errtypes.NotSupported("hellofs: commit upload not supported") } +func (fs *hellofs) PrepareUpload(_ context.Context, _ *provider.Reference, _ string, info storage.UploadInfo) (*storage.PrepareUploadResult, error) { + return &storage.PrepareUploadResult{VersionCreated: info.NodeExisted}, nil +} + +func (fs *hellofs) RollbackUpload(_ context.Context, _ *provider.Reference, _ string, _ storage.RollbackInfo) error { + return nil +} + // grants // DenyGrant marks a resource as denied for a recipient @@ -151,8 +149,8 @@ func (fs *hellofs) GetLock(ctx context.Context, ref *provider.Reference) (*provi } // SetLock puts a lock on the given reference -func (fs *hellofs) SetLock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) error { - return errtypes.NotSupported("unimplemented") +func (fs *hellofs) SetLock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) (*storage.SetLockResult, error) { + return nil, errtypes.NotSupported("unimplemented") } // RefreshLock refreshes an existing lock on the given reference @@ -161,8 +159,8 @@ func (fs *hellofs) RefreshLock(ctx context.Context, ref *provider.Reference, loc } // Unlock removes an existing lock from the given reference -func (fs *hellofs) Unlock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) error { - return errtypes.NotSupported("unimplemented") +func (fs *hellofs) Unlock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) (*storage.UnlockResult, error) { + return nil, errtypes.NotSupported("unimplemented") } // revisions @@ -178,8 +176,8 @@ func (fs *hellofs) DownloadRevision(ctx context.Context, ref *provider.Reference } // RestoreRevision restores a revision -func (fs *hellofs) RestoreRevision(ctx context.Context, ref *provider.Reference, revisionKey string) error { - return errtypes.NotSupported("unimplemented") +func (fs *hellofs) RestoreRevision(ctx context.Context, ref *provider.Reference, revisionKey string) (*storage.RestoreRevisionResult, error) { + return nil, errtypes.NotSupported("unimplemented") } // trash @@ -201,8 +199,8 @@ func (fs *hellofs) ListRecycle(ctx context.Context, ref *provider.Reference, key // RestoreRecycleItem restores an item from the recyle bin // if restoreRef is nil the resource should be restored at the original path -func (fs *hellofs) RestoreRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string, restoreRef *provider.Reference) error { - return errtypes.NotSupported("unimplemented") +func (fs *hellofs) RestoreRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string, restoreRef *provider.Reference) (*storage.RestoreRecycleItemResult, error) { + return nil, errtypes.NotSupported("unimplemented") } // CreateHome creates a users home diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/nextcloud/nextcloud.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/nextcloud/nextcloud.go index 6b152c2cda..1b90cda3a8 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/nextcloud/nextcloud.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/nextcloud/nextcloud.go @@ -21,7 +21,6 @@ package nextcloud import ( "context" "encoding/json" - "fmt" "io" "net/http" "net/url" @@ -257,34 +256,55 @@ func (nc *StorageDriver) CreateHome(ctx context.Context) error { } // CreateDir as defined in the storage.FS interface -func (nc *StorageDriver) CreateDir(ctx context.Context, ref *provider.Reference) error { +func (nc *StorageDriver) CreateDir(ctx context.Context, ref *provider.Reference) (*storage.CreateDirResult, error) { bodyStr, err := json.Marshal(ref) if err != nil { - return err + return nil, err } log := appctx.GetLogger(ctx) log.Info().Msgf("CreateDir %s", bodyStr) _, _, err = nc.do(ctx, Action{"CreateDir", string(bodyStr)}) - return err + if err != nil { + return nil, err + } + return &storage.CreateDirResult{}, nil } // TouchFile as defined in the storage.FS interface -func (nc *StorageDriver) TouchFile(ctx context.Context, ref *provider.Reference, markprocessing bool, mtime string) error { - return fmt.Errorf("unimplemented: TouchFile") +func (nc *StorageDriver) TouchFile(ctx context.Context, ref *provider.Reference, markprocessing bool, mtime string) (*storage.TouchFileResult, error) { + type paramsObj struct { + Ref *provider.Reference `json:"ref"` + MarkProcessing bool `json:"markprocessing"` + MTime string `json:"mtime"` + } + bodyStr, err := json.Marshal(¶msObj{Ref: ref, MarkProcessing: markprocessing, MTime: mtime}) + if err != nil { + return nil, err + } + log := appctx.GetLogger(ctx) + log.Info().Msgf("TouchFile %s", bodyStr) + + if _, _, err = nc.do(ctx, Action{"TouchFile", string(bodyStr)}); err != nil { + return nil, err + } + return &storage.TouchFileResult{}, nil } // Delete as defined in the storage.FS interface -func (nc *StorageDriver) Delete(ctx context.Context, ref *provider.Reference) error { +func (nc *StorageDriver) Delete(ctx context.Context, ref *provider.Reference) (*storage.DeleteResult, error) { bodyStr, err := json.Marshal(ref) if err != nil { - return err + return nil, err } log := appctx.GetLogger(ctx) log.Info().Msgf("Delete %s", bodyStr) _, _, err = nc.do(ctx, Action{"Delete", string(bodyStr)}) - return err + if err != nil { + return nil, err + } + return &storage.DeleteResult{}, nil } // Move as defined in the storage.FS interface @@ -302,7 +322,10 @@ func (nc *StorageDriver) Move(ctx context.Context, oldRef, newRef *provider.Refe log.Info().Msgf("Move %s", bodyStr) _, _, err := nc.do(ctx, Action{"Move", string(bodyStr)}) - return nil, err + if err != nil { + return nil, err + } + return &storage.MoveResult{}, nil } // GetMD as defined in the storage.FS interface @@ -372,58 +395,28 @@ func (nc *StorageDriver) ListFolder(ctx context.Context, ref *provider.Reference return pointers, err } -// InitiateUpload as defined in the storage.FS interface -func (nc *StorageDriver) InitiateUpload(ctx context.Context, ref *provider.Reference, uploadLength int64, metadata map[string]string) (map[string]string, error) { - type paramsObj struct { - Ref *provider.Reference `json:"ref"` - UploadLength int64 `json:"uploadLength"` - Metadata map[string]string `json:"metadata"` - } - bodyObj := ¶msObj{ - Ref: ref, - UploadLength: uploadLength, - Metadata: metadata, - } - bodyStr, _ := json.Marshal(bodyObj) - log := appctx.GetLogger(ctx) - log.Info().Msgf("InitiateUpload %s", bodyStr) - - _, respBody, err := nc.do(ctx, Action{"InitiateUpload", string(bodyStr)}) - if err != nil { - return nil, err - } - respMap := make(map[string]string) - err = json.Unmarshal(respBody, &respMap) - if err != nil { - return nil, err - } - return respMap, err -} - -// MarkProcessing as defined in the storage.FS interface -func (nc *StorageDriver) MarkProcessing(ctx context.Context, ref *provider.Reference, processing bool, sessionID string) error { - return errtypes.NotSupported("nextcloud: mark processing not supported") +// MarkProcessing as defined in the storage.FS interface. +// No sciencemesh endpoint toggles the flag alone. A no-op, not NotSupported: +// the coordinator treats a failed mark as fatal. +func (nc *StorageDriver) MarkProcessing(_ context.Context, _ *provider.Reference, _ bool, _ string) error { + return nil } // CommitUpload as defined in the storage.FS interface -func (nc *StorageDriver) CommitUpload(_ context.Context, _ *provider.Reference, _ string, _ storage.UploadSource) error { - return errtypes.NotSupported("nextcloud: commit upload not supported") +func (nc *StorageDriver) CommitUpload(ctx context.Context, ref *provider.Reference, _ string, source storage.UploadSource) error { + if source.Body == nil { + // A nil body would PUT an empty request and truncate the file. + return errtypes.BadRequest("nextcloud: source body is nil") + } + return nc.doUpload(ctx, ref.GetPath(), source.Body) } -// Upload as defined in the storage.FS interface -func (nc *StorageDriver) Upload(ctx context.Context, req storage.UploadRequest, _ storage.UploadFinishedFunc) (*provider.ResourceInfo, error) { - err := nc.doUpload(ctx, req.Ref.Path, req.Body) - if err != nil { - return &provider.ResourceInfo{}, err - } +func (nc *StorageDriver) PrepareUpload(_ context.Context, _ *provider.Reference, _ string, info storage.UploadInfo) (*storage.PrepareUploadResult, error) { + return &storage.PrepareUploadResult{VersionCreated: info.NodeExisted}, nil +} - // return id, etag and mtime - ri, err := nc.GetMD(ctx, req.Ref, []string{}, []string{"id", "etag", "mtime"}) - if err != nil { - return &provider.ResourceInfo{}, err - } - - return ri, nil +func (nc *StorageDriver) RollbackUpload(_ context.Context, _ *provider.Reference, _ string, _ storage.RollbackInfo) error { + return nil } // Download as defined in the storage.FS interface @@ -515,7 +508,7 @@ func (nc *StorageDriver) DownloadRevision(ctx context.Context, ref *provider.Ref } // RestoreRevision as defined in the storage.FS interface -func (nc *StorageDriver) RestoreRevision(ctx context.Context, ref *provider.Reference, key string) error { +func (nc *StorageDriver) RestoreRevision(ctx context.Context, ref *provider.Reference, key string) (*storage.RestoreRevisionResult, error) { type paramsObj struct { Ref *provider.Reference `json:"ref"` Key string `json:"key"` @@ -529,7 +522,10 @@ func (nc *StorageDriver) RestoreRevision(ctx context.Context, ref *provider.Refe log.Info().Msgf("RestoreRevision %s", bodyStr) _, _, err := nc.do(ctx, Action{"RestoreRevision", string(bodyStr)}) - return err + if err != nil { + return nil, err + } + return &storage.RestoreRevisionResult{}, nil } // ListRecycle as defined in the storage.FS interface @@ -564,7 +560,7 @@ func (nc *StorageDriver) ListRecycle(ctx context.Context, ref *provider.Referenc } // RestoreRecycleItem as defined in the storage.FS interface -func (nc *StorageDriver) RestoreRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string, restoreRef *provider.Reference) error { +func (nc *StorageDriver) RestoreRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string, restoreRef *provider.Reference) (*storage.RestoreRecycleItemResult, error) { type paramsObj struct { Key string `json:"key"` Path string `json:"path"` @@ -581,8 +577,10 @@ func (nc *StorageDriver) RestoreRecycleItem(ctx context.Context, ref *provider.R log.Info().Msgf("RestoreRecycleItem %s", bodyStr) _, _, err := nc.do(ctx, Action{"RestoreRecycleItem", string(bodyStr)}) - - return err + if err != nil { + return nil, err + } + return &storage.RestoreRecycleItemResult{}, nil } // PurgeRecycleItem as defined in the storage.FS interface @@ -858,8 +856,8 @@ func (nc *StorageDriver) GetLock(ctx context.Context, ref *provider.Reference) ( } // SetLock puts a lock on the given reference -func (nc *StorageDriver) SetLock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) error { - return errtypes.NotSupported("unimplemented") +func (nc *StorageDriver) SetLock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) (*storage.SetLockResult, error) { + return nil, errtypes.NotSupported("unimplemented") } // RefreshLock refreshes an existing lock on the given reference @@ -868,8 +866,8 @@ func (nc *StorageDriver) RefreshLock(ctx context.Context, ref *provider.Referenc } // Unlock removes an existing lock from the given reference -func (nc *StorageDriver) Unlock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) error { - return errtypes.NotSupported("unimplemented") +func (nc *StorageDriver) Unlock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) (*storage.UnlockResult, error) { + return nil, errtypes.NotSupported("unimplemented") } // AddLabel adds a label to a resource @@ -934,16 +932,16 @@ func (nc *StorageDriver) UpdateStorageSpace(ctx context.Context, req *provider.U } // DeleteStorageSpace deletes a storage space -func (nc *StorageDriver) DeleteStorageSpace(ctx context.Context, req *provider.DeleteStorageSpaceRequest) error { +func (nc *StorageDriver) DeleteStorageSpace(ctx context.Context, req *provider.DeleteStorageSpaceRequest) (*storage.DeleteStorageSpaceResult, error) { bodyStr, _ := json.Marshal(req) _, respBody, err := nc.do(ctx, Action{"DeleteStorageSpace", string(bodyStr)}) if err != nil { - return err + return nil, err } var respObj provider.DeleteStorageSpaceResponse err = json.Unmarshal(respBody, &respObj) if err != nil { - return err + return nil, err } - return nil + return &storage.DeleteStorageSpaceResult{}, nil } diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/nextcloud/nextcloud_server_mock.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/nextcloud/nextcloud_server_mock.go index 5bfdfe8b5c..bd3207cd34 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/nextcloud/nextcloud_server_mock.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/nextcloud/nextcloud_server_mock.go @@ -74,6 +74,11 @@ var responses = map[string]Response{ `POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/EmptyRecycle `: {200, ``, serverStateEmpty}, + `POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/GetQuota `: {200, `{"totalBytes":456,"usedBytes":123}`, serverStateEmpty}, + + // the parent of an upload target, stated for its permissions and its id + `POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/GetMD {"ref":{"path":"/"},"mdKeys":[]} EMPTY`: {200, `{"opaque":{},"type":2,"id":{"opaque_id":"fileid-/"},"checksum":{},"etag":"deadbeef","mime_type":"httpd/unix-directory","mtime":{"seconds":1234567890},"path":"/","permission_set":{"initiate_file_upload":true,"stat":true,"list_container":true},"size":12345,"canonical_metadata":{},"arbitrary_metadata":{"metadata":{}}}`, serverStateEmpty}, + `POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/GetMD {"ref":{"path":"/"},"mdKeys":null} EMPTY`: {404, ``, serverStateEmpty}, `POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/GetMD {"ref":{"path":"/"},"mdKeys":null} HOME`: {200, `{"opaque":{},"type":1,"id":{"opaque_id":"fileid-/some/path"},"checksum":{},"etag":"deadbeef","mime_type":"text/plain","mtime":{"seconds":1234567890},"path":"/","permission_set":{},"size":12345,"canonical_metadata":{},"arbitrary_metadata":{"metadata":{"da":"ta","some":"arbi","trary":"meta"}}}`, serverStateHome}, @@ -109,9 +114,21 @@ var responses = map[string]Response{ `POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/GetMD {"ref":{"path":"/versionedFile"},"mdKeys":null} EMPTY`: {200, `{"opaque":{},"type":1,"id":{"opaque_id":"fileid-/some/path"},"checksum":{},"etag":"deadbeef","mime_type":"text/plain","mtime":{"seconds":1234567890},"path":"/versionedFile","permission_set":{},"size":2,"canonical_metadata":{},"arbitrary_metadata":{"metadata":{"da":"ta","some":"arbi","trary":"meta"}}}`, serverStateEmpty}, `POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/GetMD {"ref":{"path":"/versionedFile"},"mdKeys":null} FILE-RESTORED`: {200, `{"opaque":{},"type":1,"id":{"opaque_id":"fileid-/some/path"},"checksum":{},"etag":"deadbeef","mime_type":"text/plain","mtime":{"seconds":1234567890},"path":"/versionedFile","permission_set":{},"size":1,"canonical_metadata":{},"arbitrary_metadata":{"metadata":{"da":"ta","some":"arbi","trary":"meta"}}}`, serverStateFileRestored}, + // The coordinator resolves the upload target itself, so it stats the file with the + // full reference before every upload. Reporting the file as existing keeps it on the + // overwrite path, which needs neither a parent stat nor a TouchFile (whose mtime is + // wall-clock derived and could never match this table's exact-body keys). + `POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/GetMD {"ref":{"resource_id":{"storage_id":"f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c"},"path":"/versionedFile"},"mdKeys":[]}`: {200, `{"opaque":{},"type":1,"id":{"storage_id":"f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c","opaque_id":"fileid-/versionedFile"},"parent_id":{"opaque_id":"fileid-/"},"name":"versionedFile","checksum":{},"etag":"deadbeef","mime_type":"text/plain","mtime":{"seconds":1234567890},"path":"/versionedFile","permission_set":{"initiate_file_upload":true,"stat":true,"list_container":true,"list_file_versions":true,"restore_file_version":true},"size":1,"canonical_metadata":{},"arbitrary_metadata":{"metadata":{}}}`, serverStateEmpty}, + `POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/GetPathByID {"storage_id":"00000000-0000-0000-0000-000000000000","opaque_id":"fileid-/some/path"} EMPTY`: {200, "/subdir", serverStateEmpty}, - `POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/GetMD {"ref":{"path":"/file"},"mdKeys":null}`: {404, ``, serverStateEmpty}, + `POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/GetMD {"ref":{"path":"/file"},"mdKeys":null}`: {404, ``, serverStateEmpty}, + // the coordinator resolves the upload target itself: the file does not exist yet, + // so it stats the parent for the permissions and the parent id + `POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/GetMD {"ref":{"path":"/file"},"mdKeys":[]}`: {404, ``, serverStateEmpty}, + // a zero-length upload finishes at once, so the node is created and read back here + `POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/TouchFile {"ref":{"resource_id":{"opaque_id":"fileid-/"},"path":"file"},"markprocessing":false,"mtime":"1234567890"}`: {200, ``, serverStateEmpty}, + `POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/GetMD {"ref":{"resource_id":{"opaque_id":"fileid-/"},"path":"file"},"mdKeys":null}`: {200, `{"opaque":{},"type":1,"id":{"opaque_id":"fileid-/file"},"checksum":{},"etag":"deadbeef","mime_type":"text/plain","mtime":{"seconds":1234567890},"path":"/file","permission_set":{},"size":0,"canonical_metadata":{},"arbitrary_metadata":{"metadata":{}}}`, serverStateEmpty}, `POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/InitiateUpload {"ref":{"path":"/file"},"uploadLength":0,"metadata":{"providerID":""}}`: {200, `{"simple": "yes","tus": "yes"}`, serverStateEmpty}, `POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/InitiateUpload {"ref":{"resource_id":{"storage_id":"f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c"},"path":"/versionedFile"},"uploadLength":1,"metadata":{}}`: {200, `{"simple": "yes","tus": "yes"}`, serverStateEmpty}, `POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/InitiateUpload {"ref":{"resource_id":{"storage_id":"f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c"},"path":"/versionedFile"},"uploadLength":2,"metadata":{}}`: {200, `{"simple": "yes","tus": "yes"}`, serverStateEmpty}, @@ -160,6 +177,7 @@ var responses = map[string]Response{ `POST /apps/sciencemesh/~tester/api/storage/ListFolder {"ref":{"resource_id":{"storage_id":"storage-id","opaque_id":"opaque-id"},"path":"/some"},"mdKeys":["val1","val2","val3"]}`: {200, `[{"opaque":{},"type":1,"id":{"opaque_id":"fileid-/some/path"},"checksum":{},"etag":"deadbeef","mime_type":"text/plain","mtime":{"seconds":1234567890},"path":"/some/path","permission_set":{},"size":12345,"canonical_metadata":{},"arbitrary_metadata":{"metadata":{"da":"ta","some":"arbi","trary":"meta"}}}]`, serverStateEmpty}, // `POST /apps/sciencemesh/~tester/api/storage/ListFolder {"ref":{"resource_id":{"storage_id":"storage-id","opaque_id":"opaque-id"},"path":"/some"},"mdKeys":["val1","val2","val3"]}`: {200, `[{"opaque":{},"type":1,"id":{"opaque_id":"fileid-/path"},"checksum":{},"etag":"deadbeef","mime_type":"text/plain","mtime":{"seconds":1234567890},"path":"/path","permission_set":{},"size":12345,"canonical_metadata":{},"arbitrary_metadata":{"metadata":{"da":"ta","some":"arbi","trary":"meta"}}}]`, serverStateEmpty}, `POST /apps/sciencemesh/~tester/api/storage/InitiateUpload {"ref":{"resource_id":{"storage_id":"storage-id","opaque_id":"opaque-id"},"path":"/some/path"},"uploadLength":12345,"metadata":{"key1":"val1","key2":"val2","key3":"val3"}}`: {200, `{ "not":"sure", "what": "should be", "returned": "here" }`, serverStateEmpty}, + `POST /apps/sciencemesh/~tester/api/storage/TouchFile {"ref":{"resource_id":{"storage_id":"storage-id","opaque_id":"opaque-id"},"path":"some/file/path.txt"},"markprocessing":false,"mtime":"1234567890"}`: {200, ``, serverStateEmpty}, `PUT /apps/sciencemesh/~tester/api/storage/Upload/some/file/path.txt shiny!`: {200, ``, serverStateEmpty}, `POST /apps/sciencemesh/~tester/api/storage/GetMD {"ref":{"resource_id":{"storage_id":"storage-id","opaque_id":"opaque-id"},"path":"some/file/path.txt"},"mdKeys":[]}`: {200, `{"opaque":{},"type":1,"id":{"opaque_id":"fileid-/some/path"},"checksum":{},"etag":"deadbeef","mime_type":"text/plain","mtime":{"seconds":1234567890},"path":"/versionedFile","permission_set":{},"size":12345,"canonical_metadata":{},"arbitrary_metadata":{"metadata":{"key1":"val1","key2":"val2","key3":"val3"}}}`, serverStateEmpty}, `GET /apps/sciencemesh/~tester/api/storage/Download/some/file/path.txt `: {200, `the contents of the file`, serverStateEmpty}, diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/owncloudsql/owncloudsql.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/owncloudsql/owncloudsql.go index da2db84ec1..a67e497300 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/owncloudsql/owncloudsql.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/owncloudsql/owncloudsql.go @@ -754,38 +754,38 @@ func (fs *owncloudsqlfs) GetHome(ctx context.Context) (string, error) { return "", nil } -func (fs *owncloudsqlfs) CreateDir(ctx context.Context, ref *provider.Reference) (err error) { +func (fs *owncloudsqlfs) CreateDir(ctx context.Context, ref *provider.Reference) (_ *storage.CreateDirResult, err error) { ip, err := fs.resolve(ctx, ref) if err != nil { - return err + return nil, err } // check permissions of parent dir if perm, err := fs.readPermissions(ctx, filepath.Dir(ip)); err == nil { if !perm.CreateContainer { - return errtypes.PermissionDenied("") + return nil, errtypes.PermissionDenied("") } } else { if isNotFound(err) { - return errtypes.PreconditionFailed(ref.Path) + return nil, errtypes.PreconditionFailed(ref.Path) } - return errors.Wrap(err, "owncloudsql: error reading permissions") + return nil, errors.Wrap(err, "owncloudsql: error reading permissions") } if err = os.Mkdir(ip, 0700); err != nil { if os.IsNotExist(err) { - return errtypes.PreconditionFailed(ref.Path) + return nil, errtypes.PreconditionFailed(ref.Path) } if os.IsExist(err) { - return errtypes.AlreadyExists(ref.Path) + return nil, errtypes.AlreadyExists(ref.Path) } - return errors.Wrap(err, "owncloudsql: error creating dir "+fs.toStoragePath(ctx, filepath.Dir(ip))) + return nil, errors.Wrap(err, "owncloudsql: error creating dir "+fs.toStoragePath(ctx, filepath.Dir(ip))) } fi, err := os.Stat(ip) if err != nil { - return err + return nil, err } mtime := time.Now().Unix() @@ -803,54 +803,55 @@ func (fs *owncloudsqlfs) CreateDir(ctx context.Context, ref *provider.Reference) } storageID, err := fs.getStorage(ctx, ip) if err != nil { - return err + return nil, err } _, err = fs.filecache.InsertOrUpdate(ctx, storageID, data, false) if err != nil { - if err != nil { - return err - } + return nil, err } - return fs.propagate(ctx, filepath.Dir(ip)) + if err := fs.propagate(ctx, filepath.Dir(ip)); err != nil { + return nil, err + } + return &storage.CreateDirResult{}, nil } // TouchFile as defined in the storage.FS interface -func (fs *owncloudsqlfs) TouchFile(ctx context.Context, ref *provider.Reference, markprocessing bool, mtime string) error { +func (fs *owncloudsqlfs) TouchFile(ctx context.Context, ref *provider.Reference, markprocessing bool, mtime string) (*storage.TouchFileResult, error) { ip, err := fs.resolve(ctx, ref) if err != nil { - return err + return nil, err } // check permissions of parent dir parentPerms, err := fs.readPermissions(ctx, filepath.Dir(ip)) if err == nil { if !parentPerms.InitiateFileUpload { - return errtypes.PermissionDenied("") + return nil, errtypes.PermissionDenied("") } } else { if isNotFound(err) { - return errtypes.NotFound(ref.Path) + return nil, errtypes.NotFound(ref.Path) } - return errors.Wrap(err, "owncloudsql: error reading permissions") + return nil, errors.Wrap(err, "owncloudsql: error reading permissions") } _, err = os.Create(ip) if err != nil { if os.IsNotExist(err) { - return errtypes.NotFound(ref.Path) + return nil, errtypes.NotFound(ref.Path) } // FIXME we also need already exists error, webdav expects 405 MethodNotAllowed - return errors.Wrap(err, "owncloudsql: error creating file "+fs.toStoragePath(ctx, filepath.Dir(ip))) + return nil, errors.Wrap(err, "owncloudsql: error creating file "+fs.toStoragePath(ctx, filepath.Dir(ip))) } if err = os.Chmod(ip, 0700); err != nil { - return errors.Wrap(err, "owncloudsql: error setting file permissions on "+fs.toStoragePath(ctx, filepath.Dir(ip))) + return nil, errors.Wrap(err, "owncloudsql: error setting file permissions on "+fs.toStoragePath(ctx, filepath.Dir(ip))) } fi, err := os.Stat(ip) if err != nil { - return err + return nil, err } storageMtime := time.Now().Unix() mt := storageMtime @@ -874,14 +875,17 @@ func (fs *owncloudsqlfs) TouchFile(ctx context.Context, ref *provider.Reference, } storageID, err := fs.getStorage(ctx, ip) if err != nil { - return err + return nil, err } _, err = fs.filecache.InsertOrUpdate(ctx, storageID, data, false) if err != nil { - return err + return nil, err } - return fs.propagate(ctx, filepath.Dir(ip)) + if err := fs.propagate(ctx, filepath.Dir(ip)); err != nil { + return nil, err + } + return &storage.TouchFileResult{}, nil } func (fs *owncloudsqlfs) CreateReference(ctx context.Context, sp string, targetURI *url.URL) error { @@ -1151,8 +1155,8 @@ func (fs *owncloudsqlfs) GetLock(ctx context.Context, ref *provider.Reference) ( } // SetLock puts a lock on the given reference -func (fs *owncloudsqlfs) SetLock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) error { - return errtypes.NotSupported("unimplemented") +func (fs *owncloudsqlfs) SetLock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) (*storage.SetLockResult, error) { + return nil, errtypes.NotSupported("unimplemented") } // RefreshLock refreshes an existing lock on the given reference @@ -1161,8 +1165,8 @@ func (fs *owncloudsqlfs) RefreshLock(ctx context.Context, ref *provider.Referenc } // Unlock removes an existing lock from the given reference -func (fs *owncloudsqlfs) Unlock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) error { - return errtypes.NotSupported("unimplemented") +func (fs *owncloudsqlfs) Unlock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) (*storage.UnlockResult, error) { + return nil, errtypes.NotSupported("unimplemented") } // Delete is actually only a move to trash @@ -1174,40 +1178,40 @@ func (fs *owncloudsqlfs) Unlock(ctx context.Context, ref *provider.Reference, lo // versions were not. // We will live with that compromise since this storage driver will be // deprecated soon. -func (fs *owncloudsqlfs) Delete(ctx context.Context, ref *provider.Reference) (err error) { +func (fs *owncloudsqlfs) Delete(ctx context.Context, ref *provider.Reference) (_ *storage.DeleteResult, err error) { var ip string if ip, err = fs.resolve(ctx, ref); err != nil { - return errors.Wrap(err, "owncloudsql: error resolving reference") + return nil, errors.Wrap(err, "owncloudsql: error resolving reference") } // check permissions if perm, err := fs.readPermissions(ctx, ip); err == nil { if !perm.Delete { - return errtypes.PermissionDenied("") + return nil, errtypes.PermissionDenied("") } } else { if isNotFound(err) { - return errtypes.NotFound(fs.toStoragePath(ctx, filepath.Dir(ip))) + return nil, errtypes.NotFound(fs.toStoragePath(ctx, filepath.Dir(ip))) } - return errors.Wrap(err, "owncloudsql: error reading permissions") + return nil, errors.Wrap(err, "owncloudsql: error reading permissions") } _, err = os.Stat(ip) if err != nil { if os.IsNotExist(err) { - return errtypes.NotFound(fs.toStoragePath(ctx, ip)) + return nil, errtypes.NotFound(fs.toStoragePath(ctx, ip)) } - return errors.Wrap(err, "owncloudsql: error stating "+ip) + return nil, errors.Wrap(err, "owncloudsql: error stating "+ip) } // Delete file into the owner's trash, not the user's (in case of shares) rp, err := fs.getRecyclePathForUser(fs.getOwner(ip)) if err != nil { - return errors.Wrap(err, "owncloudsql: error resolving recycle path") + return nil, errors.Wrap(err, "owncloudsql: error resolving recycle path") } if err := os.MkdirAll(rp, 0700); err != nil { - return errors.Wrap(err, "owncloudsql: error creating trashbin dir "+rp) + return nil, errors.Wrap(err, "owncloudsql: error creating trashbin dir "+rp) } // ip is the path on disk ... we need only the path relative to root @@ -1215,9 +1219,9 @@ func (fs *owncloudsqlfs) Delete(ctx context.Context, ref *provider.Reference) (e err = fs.trash(ctx, ip, rp, origin) if err != nil { - return errors.Wrapf(err, "owncloudsql: error deleting file %s", ip) + return nil, errors.Wrapf(err, "owncloudsql: error deleting file %s", ip) } - return nil + return &storage.DeleteResult{}, nil } func (fs *owncloudsqlfs) trash(ctx context.Context, ip string, rp string, origin string) error { @@ -1347,7 +1351,7 @@ func (fs *owncloudsqlfs) Move(ctx context.Context, oldRef, newRef *provider.Refe return nil, err } } - return nil, nil + return &storage.MoveResult{}, nil } func (fs *owncloudsqlfs) GetMD(ctx context.Context, ref *provider.Reference, mdKeys []string, fieldMask []string) (*provider.ResourceInfo, error) { @@ -1665,22 +1669,22 @@ func (fs *owncloudsqlfs) DownloadRevision(ctx context.Context, ref *provider.Ref return nil, nil, errtypes.NotSupported("download revision") } -func (fs *owncloudsqlfs) RestoreRevision(ctx context.Context, ref *provider.Reference, revisionKey string) error { +func (fs *owncloudsqlfs) RestoreRevision(ctx context.Context, ref *provider.Reference, revisionKey string) (*storage.RestoreRevisionResult, error) { ip, err := fs.resolve(ctx, ref) if err != nil { - return errors.Wrap(err, "owncloudsql: error resolving reference") + return nil, errors.Wrap(err, "owncloudsql: error resolving reference") } // check permissions if perm, err := fs.readPermissions(ctx, ip); err == nil { if !perm.RestoreFileVersion { - return errtypes.PermissionDenied("") + return nil, errtypes.PermissionDenied("") } } else { if isNotFound(err) { - return errtypes.NotFound(fs.toStoragePath(ctx, filepath.Dir(ip))) + return nil, errtypes.NotFound(fs.toStoragePath(ctx, filepath.Dir(ip))) } - return errors.Wrap(err, "owncloudsql: error reading permissions") + return nil, errors.Wrap(err, "owncloudsql: error reading permissions") } vp := fs.getVersionsPath(ctx, ip) @@ -1689,34 +1693,34 @@ func (fs *owncloudsqlfs) RestoreRevision(ctx context.Context, ref *provider.Refe // check revision exists rs, err := os.Stat(rp) if err != nil { - return err + return nil, err } if !rs.Mode().IsRegular() { - return fmt.Errorf("%s is not a regular file", rp) + return nil, fmt.Errorf("%s is not a regular file", rp) } source, err := os.Open(rp) if err != nil { - return err + return nil, err } defer source.Close() // destination should be available, otherwise we could not have navigated to its revisions if err := fs.archiveRevision(ctx, fs.getVersionsPath(ctx, ip), ip); err != nil { - return err + return nil, err } destination, err := os.Create(ip) if err != nil { // TODO(jfd) bring back revision in case sth goes wrong? - return err + return nil, err } defer destination.Close() _, err = io.Copy(destination, source) if err != nil { - return err + return nil, err } sha1h, md5h, adler32h, err := fs.HashFile(ip) @@ -1725,7 +1729,7 @@ func (fs *owncloudsqlfs) RestoreRevision(ctx context.Context, ref *provider.Refe } fi, err := os.Stat(ip) if err != nil { - return err + return nil, err } mtime := time.Now().Unix() data := map[string]interface{}{ @@ -1739,15 +1743,18 @@ func (fs *owncloudsqlfs) RestoreRevision(ctx context.Context, ref *provider.Refe } storageID, err := fs.getStorage(ctx, ip) if err != nil { - return err + return nil, err } _, err = fs.filecache.InsertOrUpdate(ctx, storageID, data, false) if err != nil { - return err + return nil, err } // TODO(jfd) bring back revision in case sth goes wrong? - return fs.propagate(ctx, ip) + if err := fs.propagate(ctx, ip); err != nil { + return nil, err + } + return &storage.RestoreRevisionResult{}, nil } func (fs *owncloudsqlfs) PurgeRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string) error { @@ -1910,18 +1917,18 @@ func (fs *owncloudsqlfs) ListRecycle(ctx context.Context, ref *provider.Referenc return items, nil } -func (fs *owncloudsqlfs) RestoreRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string, restoreRef *provider.Reference) error { +func (fs *owncloudsqlfs) RestoreRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string, restoreRef *provider.Reference) (*storage.RestoreRecycleItemResult, error) { log := appctx.GetLogger(ctx) base, ttime, err := splitTrashKey(key) if err != nil { log.Error().Str("path", key).Msg("invalid trash item key") - return fmt.Errorf("invalid trash item suffix") + return nil, fmt.Errorf("invalid trash item suffix") } recyclePath, err := fs.getRecyclePath(ctx) if err != nil { - return errors.Wrap(err, "owncloudsql: error resolving recycle path") + return nil, errors.Wrap(err, "owncloudsql: error resolving recycle path") } src := filepath.Join(recyclePath, filepath.Clean(key)) @@ -1931,7 +1938,7 @@ func (fs *owncloudsqlfs) RestoreRecycleItem(ctx context.Context, ref *provider.R if err != nil { log := appctx.GetLogger(ctx) log.Error().Err(err).Str("path", key).Msg("could not get trash item") - return nil + return nil, err } restoreRef.Path = filepath.Join(item.Path, item.Name) } @@ -1940,27 +1947,30 @@ func (fs *owncloudsqlfs) RestoreRecycleItem(ctx context.Context, ref *provider.R // move back to original location if err := os.Rename(src, tgt); err != nil { log.Error().Err(err).Str("key", key).Str("restorePath", restoreRef.Path).Str("src", src).Str("tgt", tgt).Msg("could not restore item") - return errors.Wrap(err, "owncloudsql: could not restore item") + return nil, errors.Wrap(err, "owncloudsql: could not restore item") } - storage, err := fs.getStorage(ctx, src) + storageID, err := fs.getStorage(ctx, src) if err != nil { - return err + return nil, err } - err = fs.filecache.Move(ctx, storage, fs.toDatabasePath(src), fs.toDatabasePath(tgt)) + err = fs.filecache.Move(ctx, storageID, fs.toDatabasePath(src), fs.toDatabasePath(tgt)) if err != nil { - return err + return nil, err } err = fs.filecache.DeleteRecycleItem(ctx, ctxpkg.ContextMustGetUser(ctx).Username, base, ttime) if err != nil { - return err + return nil, err } err = fs.RestoreRecycleItemVersions(ctx, key, tgt) if err != nil { - return err + return nil, err } - return fs.propagate(ctx, tgt) + if err := fs.propagate(ctx, tgt); err != nil { + return nil, err + } + return &storage.RestoreRecycleItemResult{}, nil } func (fs *owncloudsqlfs) RestoreRecycleItemVersions(ctx context.Context, key, target string) error { diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/owncloudsql/spaces.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/owncloudsql/spaces.go index 0aaeddf39f..5cfda5e9d5 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/owncloudsql/spaces.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/owncloudsql/spaces.go @@ -29,6 +29,7 @@ import ( types "github.com/cs3org/go-cs3apis/cs3/types/v1beta1" ctxpkg "github.com/opencloud-eu/reva/v2/pkg/ctx" "github.com/opencloud-eu/reva/v2/pkg/errtypes" + "github.com/opencloud-eu/reva/v2/pkg/storage" "github.com/opencloud-eu/reva/v2/pkg/storage/fs/owncloudsql/filecache" "github.com/opencloud-eu/reva/v2/pkg/storagespace" "github.com/opencloud-eu/reva/v2/pkg/utils" @@ -104,8 +105,8 @@ func (fs *owncloudsqlfs) UpdateStorageSpace(ctx context.Context, req *provider.U } // DeleteStorageSpace deletes a storage space -func (fs *owncloudsqlfs) DeleteStorageSpace(ctx context.Context, req *provider.DeleteStorageSpaceRequest) error { - return errtypes.NotSupported("delete storage space") +func (fs *owncloudsqlfs) DeleteStorageSpace(ctx context.Context, req *provider.DeleteStorageSpaceRequest) (*storage.DeleteStorageSpaceResult, error) { + return nil, errtypes.NotSupported("delete storage space") } // Note: currently unused but will be used later diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/owncloudsql/upload.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/owncloudsql/upload.go index 46b1cb932a..08c790fb94 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/owncloudsql/upload.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/owncloudsql/upload.go @@ -20,155 +20,12 @@ package owncloudsql import ( "context" - "encoding/json" - "fmt" - "io" - iofs "io/fs" - "os" - "path/filepath" - "strconv" - "time" - userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" - "github.com/google/uuid" - "github.com/opencloud-eu/reva/v2/pkg/appctx" - "github.com/opencloud-eu/reva/v2/pkg/conversions" - ctxpkg "github.com/opencloud-eu/reva/v2/pkg/ctx" "github.com/opencloud-eu/reva/v2/pkg/errtypes" - "github.com/opencloud-eu/reva/v2/pkg/logger" - "github.com/opencloud-eu/reva/v2/pkg/mime" "github.com/opencloud-eu/reva/v2/pkg/storage" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/chunking" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/templates" - "github.com/opencloud-eu/reva/v2/pkg/utils" - "github.com/pkg/errors" - "github.com/rs/zerolog/log" - tusd "github.com/tus/tusd/v2/pkg/handler" ) -var defaultFilePerm = os.FileMode(0664) - -func (fs *owncloudsqlfs) Upload(ctx context.Context, req storage.UploadRequest, uff storage.UploadFinishedFunc) (*provider.ResourceInfo, error) { - upload, err := fs.GetUpload(ctx, req.Ref.GetPath()) - if err != nil { - return &provider.ResourceInfo{}, errors.Wrap(err, "owncloudsql: error retrieving upload") - } - - uploadInfo := upload.(*fileUpload) - - p := uploadInfo.info.Storage["InternalDestination"] - if chunking.IsChunked(p) { - var assembledFile string - p, assembledFile, err = fs.chunkHandler.WriteChunk(p, req.Body) - if err != nil { - return &provider.ResourceInfo{}, err - } - if p == "" { - if err = uploadInfo.Terminate(ctx); err != nil { - return &provider.ResourceInfo{}, errors.Wrap(err, "owncloudsql: error removing auxiliary files") - } - return &provider.ResourceInfo{}, errtypes.PartialContent(req.Ref.String()) - } - uploadInfo.info.Storage["InternalDestination"] = p - fd, err := os.Open(assembledFile) - if err != nil { - return &provider.ResourceInfo{}, errors.Wrap(err, "owncloudsql: error opening assembled file") - } - defer fd.Close() - defer os.RemoveAll(assembledFile) - req.Body = fd - } - - if _, err := uploadInfo.WriteChunk(ctx, 0, req.Body); err != nil { - return &provider.ResourceInfo{}, errors.Wrap(err, "owncloudsql: error writing to binary file") - } - - if err := uploadInfo.FinishUpload(ctx); err != nil { - return &provider.ResourceInfo{}, err - } - - if uff != nil { - info := uploadInfo.info - uploadRef := &provider.Reference{ - ResourceId: &provider.ResourceId{ - StorageId: info.MetaData["providerID"], - SpaceId: info.Storage["SpaceRoot"], - OpaqueId: info.Storage["SpaceRoot"], - }, - Path: utils.MakeRelativePath(filepath.Join(info.MetaData["dir"], info.MetaData["filename"])), - } - owner, ok := ctxpkg.ContextGetUser(uploadInfo.ctx) - if !ok { - return &provider.ResourceInfo{}, errtypes.PreconditionFailed("error getting user from uploadinfo context") - } - // spaces support in localfs needs to be revisited: - // * info.Storage["SpaceRoot"] is never set - // * there is no space owner or manager that could be passed to the UploadFinishedFunc - uff(owner.Id, owner.Id, uploadRef) - } - - ri := &provider.ResourceInfo{ - // fill with at least fileid, mtime and etag - Id: &provider.ResourceId{ - StorageId: uploadInfo.info.MetaData["providerID"], - SpaceId: uploadInfo.info.Storage["StorageId"], - OpaqueId: uploadInfo.info.Storage["fileid"], - }, - Etag: uploadInfo.info.MetaData["etag"], - } - - if mtime, err := utils.MTimeToTS(uploadInfo.info.MetaData["mtime"]); err == nil { - ri.Mtime = &mtime - } - - return ri, nil -} - -// InitiateUpload returns upload ids corresponding to different protocols it supports -// TODO read optional content for small files in this request -func (fs *owncloudsqlfs) InitiateUpload(ctx context.Context, ref *provider.Reference, uploadLength int64, metadata map[string]string) (map[string]string, error) { - ip, err := fs.resolve(ctx, ref) - if err != nil { - return nil, errors.Wrap(err, "owncloudsql: error resolving reference") - } - - // permissions are checked in NewUpload below - - p := fs.toStoragePath(ctx, ip) - - info := tusd.FileInfo{ - MetaData: tusd.MetaData{ - "filename": filepath.Base(p), - "dir": filepath.Dir(p), - "mtime": strconv.FormatInt(time.Now().Unix(), 10), - }, - Size: uploadLength, - } - - if metadata != nil { - info.MetaData["providerID"] = metadata["providerID"] - if metadata["mtime"] != "" { - info.MetaData["mtime"] = metadata["mtime"] - } - if _, ok := metadata["sizedeferred"]; ok { - info.SizeIsDeferred = true - } - } - - upload, err := fs.NewUpload(ctx, info) - if err != nil { - return nil, err - } - - info, _ = upload.GetInfo(ctx) - - return map[string]string{ - "simple": info.ID, - "tus": info.ID, - }, nil -} - func (fs *owncloudsqlfs) MarkProcessing(ctx context.Context, ref *provider.Reference, processing bool, sessionID string) error { return errtypes.NotSupported("op not supported") } @@ -177,383 +34,10 @@ func (fs *owncloudsqlfs) CommitUpload(_ context.Context, _ *provider.Reference, return errtypes.NotSupported("op not supported") } -// UseIn tells the tus upload middleware which extensions it supports. -func (fs *owncloudsqlfs) UseIn(composer *tusd.StoreComposer) { - composer.UseCore(fs) - composer.UseTerminater(fs) - composer.UseConcater(fs) - composer.UseLengthDeferrer(fs) +func (fs *owncloudsqlfs) PrepareUpload(_ context.Context, _ *provider.Reference, _ string, info storage.UploadInfo) (*storage.PrepareUploadResult, error) { + return &storage.PrepareUploadResult{VersionCreated: info.NodeExisted}, nil } -// To implement the core tus.io protocol as specified in https://tus.io/protocols/resumable-upload.html#core-protocol -// - the storage needs to implement NewUpload and GetUpload -// - the upload needs to implement the tusd.Upload interface: WriteChunk, GetInfo, GetReader and FinishUpload - -func (fs *owncloudsqlfs) NewUpload(ctx context.Context, info tusd.FileInfo) (upload tusd.Upload, err error) { - - log := appctx.GetLogger(ctx) - log.Debug().Interface("info", info).Msg("owncloudsql: NewUpload") - - if info.MetaData["filename"] == "" { - return nil, errors.New("owncloudsql: missing filename in metadata") - } - info.MetaData["filename"] = filepath.Clean(info.MetaData["filename"]) - - dir := info.MetaData["dir"] - if dir == "" { - return nil, errors.New("owncloudsql: missing dir in metadata") - } - info.MetaData["dir"] = filepath.Clean(info.MetaData["dir"]) - - ip := fs.toInternalPath(ctx, filepath.Join(info.MetaData["dir"], info.MetaData["filename"])) - - // check permissions - var perm *provider.ResourcePermissions - var perr error - var fsInfo iofs.FileInfo - // if destination exists - if fsInfo, err = os.Stat(ip); err == nil { - // check permissions of file to be overwritten - perm, perr = fs.readPermissions(ctx, ip) - } else { - // check permissions of parent folder - perm, perr = fs.readPermissions(ctx, filepath.Dir(ip)) - } - if perr == nil { - if !perm.InitiateFileUpload { - return nil, errtypes.PermissionDenied("") - } - } else { - if os.IsNotExist(err) { - return nil, errtypes.NotFound(fs.toStoragePath(ctx, filepath.Dir(ip))) - } - return nil, errors.Wrap(err, "owncloudsql: error reading permissions") - } - - // if we are trying to overwriting a folder with a file - if fsInfo != nil && fsInfo.IsDir() { - return nil, errtypes.PreconditionFailed("resource is not a file") - } - - log.Debug().Interface("info", info).Msg("owncloudsql: resolved filename") - - info.ID = uuid.New().String() - - binPath, err := fs.getUploadPath(ctx, info.ID) - if err != nil { - return nil, errors.Wrap(err, "owncloudsql: error resolving upload path") - } - usr := ctxpkg.ContextMustGetUser(ctx) - storageID, err := fs.getStorage(ctx, ip) - if err != nil { - return nil, err - } - info.Storage = map[string]string{ - "Type": "OwnCloudStore", - "BinPath": binPath, - "InternalDestination": ip, - "Permissions": strconv.Itoa((int)(conversions.RoleFromResourcePermissions(perm, false).OCSPermissions())), - - "Idp": usr.Id.Idp, - "UserId": usr.Id.OpaqueId, - "UserName": usr.Username, - - "LogLevel": log.GetLevel().String(), - - "StorageId": strconv.Itoa(storageID), - } - // Create binary file in the upload folder with no content - log.Debug().Interface("info", info).Msg("owncloudsql: built storage info") - file, err := os.OpenFile(binPath, os.O_CREATE|os.O_WRONLY, defaultFilePerm) - if err != nil { - return nil, err - } - defer file.Close() - - u := &fileUpload{ - info: info, - binPath: binPath, - infoPath: filepath.Join(fs.c.UploadInfoDir, info.ID+".info"), - fs: fs, - ctx: ctx, - } - - // writeInfo creates the file by itself if necessary - err = u.writeInfo() - if err != nil { - return nil, err - } - - return u, nil -} - -func (fs *owncloudsqlfs) getUploadPath(ctx context.Context, uploadID string) (string, error) { - u, ok := ctxpkg.ContextGetUser(ctx) - if !ok { - err := errors.Wrap(errtypes.UserRequired("userrequired"), "error getting user from ctx") - return "", err - } - layout := templates.WithUser(u, fs.c.UserLayout) - return filepath.Join(fs.c.DataDirectory, layout, "uploads", uploadID), nil -} - -// GetUpload returns the Upload for the given upload id -func (fs *owncloudsqlfs) GetUpload(ctx context.Context, id string) (tusd.Upload, error) { - infoPath := filepath.Join(fs.c.UploadInfoDir, id+".info") - - info := tusd.FileInfo{} - data, err := os.ReadFile(infoPath) - if err != nil { - if os.IsNotExist(err) { - // Interpret os.ErrNotExist as 404 Not Found - err = tusd.ErrNotFound - } - return nil, err - } - if err := json.Unmarshal(data, &info); err != nil { - return nil, err - } - - stat, err := os.Stat(info.Storage["BinPath"]) - if err != nil { - return nil, err - } - - info.Offset = stat.Size() - - u := &userpb.User{ - Id: &userpb.UserId{ - Idp: info.Storage["Idp"], - OpaqueId: info.Storage["UserId"], - }, - Username: info.Storage["UserName"], - } - - ctx = ctxpkg.ContextSetUser(ctx, u) - // TODO configure the logger the same way ... store and add traceid in file info - - opts := []logger.Option{ - logger.WithLevel(info.Storage["LogLevel"]), - logger.WithWriter(os.Stderr, logger.ConsoleMode), - } - l := logger.New(opts...) - - sub := l.With().Int("pid", os.Getpid()).Logger() - - ctx = appctx.WithLogger(ctx, &sub) - - return &fileUpload{ - info: info, - binPath: info.Storage["BinPath"], - infoPath: infoPath, - fs: fs, - ctx: ctx, - }, nil -} - -type fileUpload struct { - // info stores the current information about the upload - info tusd.FileInfo - // infoPath is the path to the .info file - infoPath string - // binPath is the path to the binary file (which has no extension) - binPath string - // only fs knows how to handle metadata and versions - fs *owncloudsqlfs - // a context with a user - // TODO add logger as well? - ctx context.Context -} - -// GetInfo returns the FileInfo -func (upload *fileUpload) GetInfo(ctx context.Context) (tusd.FileInfo, error) { - return upload.info, nil -} - -// WriteChunk writes the stream from the reader to the given offset of the upload -func (upload *fileUpload) WriteChunk(ctx context.Context, offset int64, src io.Reader) (int64, error) { - file, err := os.OpenFile(upload.binPath, os.O_WRONLY|os.O_APPEND, defaultFilePerm) - if err != nil { - return 0, err - } - defer file.Close() - - n, err := io.Copy(file, src) - - // If the HTTP PATCH request gets interrupted in the middle (e.g. because - // the user wants to pause the upload), Go's net/http returns an io.ErrUnexpectedEOF. - // However, for OwnCloudStore it's not important whether the stream has ended - // on purpose or accidentally. - if err != nil { - if err != io.ErrUnexpectedEOF { - return n, err - } - } - - upload.info.Offset += n - err = upload.writeInfo() // TODO info is written here ... we need to truncate in DiscardChunk - - return n, err -} - -// GetReader returns an io.Reader for the upload -func (upload *fileUpload) GetReader(ctx context.Context) (io.ReadCloser, error) { - return os.Open(upload.binPath) -} - -// writeInfo updates the entire information. Everything will be overwritten. -func (upload *fileUpload) writeInfo() error { - log.Debug().Str("path", upload.infoPath).Msg("Writing info file") - data, err := json.Marshal(upload.info) - if err != nil { - return err - } - return os.WriteFile(upload.infoPath, data, defaultFilePerm) -} - -// FinishUpload finishes an upload and moves the file to the internal destination -func (upload *fileUpload) FinishUpload(ctx context.Context) error { - - ip := upload.info.Storage["InternalDestination"] - - // if destination exists - // TODO check etag with If-Match header - if _, err := os.Stat(ip); err == nil { - // create revision - if err := upload.fs.archiveRevision(upload.ctx, upload.fs.getVersionsPath(upload.ctx, ip), ip); err != nil { - return err - } - } - - sha1h, md5h, adler32h, err := upload.fs.HashFile(upload.binPath) - if err != nil { - log.Err(err).Msg("owncloudsql: could not open file for checksumming") - } - - err = os.Rename(upload.binPath, ip) - if err != nil { - log.Err(err).Interface("info", upload.info). - Str("binPath", upload.binPath). - Str("ipath", ip). - Msg("owncloudsql: could not rename") - return err - } - - var fi os.FileInfo - fi, err = os.Stat(ip) - if err != nil { - return err - } - - perms, err := strconv.Atoi(upload.info.Storage["Permissions"]) - if err != nil { - return err - } - - if upload.info.MetaData["mtime"] == "" { - upload.info.MetaData["mtime"] = fmt.Sprintf("%d", fi.ModTime().Unix()) - } - if upload.info.MetaData["etag"] == "" { - upload.info.MetaData["etag"] = calcEtag(upload.ctx, fi) - } - - data := map[string]interface{}{ - "path": upload.fs.toDatabasePath(ip), - "checksum": fmt.Sprintf("SHA1:%032x MD5:%032x ADLER32:%032x", sha1h, md5h, adler32h), - "etag": upload.info.MetaData["etag"], - "size": upload.info.Size, - "mimetype": mime.Detect(false, ip), - "permissions": perms, - "mtime": upload.info.MetaData["mtime"], - "storage_mtime": upload.info.MetaData["mtime"], - } - var fileid int - fileid, err = upload.fs.filecache.InsertOrUpdate(ctx, upload.info.Storage["StorageId"], data, false) - if err != nil { - return err - } - upload.info.Storage["fileid"] = fmt.Sprintf("%d", fileid) - - // only delete the upload if it was successfully written to the storage - if err := os.Remove(upload.infoPath); err != nil { - if !os.IsNotExist(err) { - log.Err(err).Interface("info", upload.info).Msg("owncloudsql: could not delete upload info") - return err - } - } - - return upload.fs.propagate(upload.ctx, ip) -} - -// To implement the termination extension as specified in https://tus.io/protocols/resumable-upload.html#termination -// - the storage needs to implement AsTerminatableUpload -// - the upload needs to implement Terminate - -// AsTerminatableUpload returns a TerminatableUpload -func (fs *owncloudsqlfs) AsTerminatableUpload(upload tusd.Upload) tusd.TerminatableUpload { - return upload.(*fileUpload) -} - -// Terminate terminates the upload -func (upload *fileUpload) Terminate(ctx context.Context) error { - if err := os.Remove(upload.infoPath); err != nil { - if !os.IsNotExist(err) { - return err - } - } - if err := os.Remove(upload.binPath); err != nil { - if !os.IsNotExist(err) { - return err - } - } +func (fs *owncloudsqlfs) RollbackUpload(_ context.Context, _ *provider.Reference, _ string, _ storage.RollbackInfo) error { return nil } - -// To implement the creation-defer-length extension as specified in https://tus.io/protocols/resumable-upload.html#creation -// - the storage needs to implement AsLengthDeclarableUpload -// - the upload needs to implement DeclareLength - -// AsLengthDeclarableUpload returns a LengthDeclarableUpload -func (fs *owncloudsqlfs) AsLengthDeclarableUpload(upload tusd.Upload) tusd.LengthDeclarableUpload { - return upload.(*fileUpload) -} - -// DeclareLength updates the upload length information -func (upload *fileUpload) DeclareLength(ctx context.Context, length int64) error { - upload.info.Size = length - upload.info.SizeIsDeferred = false - return upload.writeInfo() -} - -// To implement the concatenation extension as specified in https://tus.io/protocols/resumable-upload.html#concatenation -// - the storage needs to implement AsConcatableUpload -// - the upload needs to implement ConcatUploads - -// AsConcatableUpload returns a ConcatableUpload -func (fs *owncloudsqlfs) AsConcatableUpload(upload tusd.Upload) tusd.ConcatableUpload { - return upload.(*fileUpload) -} - -// ConcatUploads concatenates multiple uploads -func (upload *fileUpload) ConcatUploads(ctx context.Context, uploads []tusd.Upload) (err error) { - file, err := os.OpenFile(upload.binPath, os.O_WRONLY|os.O_APPEND, defaultFilePerm) - if err != nil { - return err - } - defer file.Close() - - for _, partialUpload := range uploads { - fileUpload := partialUpload.(*fileUpload) - - src, err := os.Open(fileUpload.binPath) - if err != nil { - return err - } - - if _, err := io.Copy(file, src); err != nil { - return err - } - } - - return -} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/posix/blobstore/blobstore.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/posix/blobstore/blobstore.go index ebb554b947..7ab03e8b26 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/posix/blobstore/blobstore.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/posix/blobstore/blobstore.go @@ -67,7 +67,10 @@ func (bs *Blobstore) Upload(n *node.Node, source, copyTarget string) error { return err } - if bs.canUseRenameForUpload { + // a source staged in the tmp dir already is the temp file (see UploadFromReader) + staged := filepath.Clean(source) == tempName + + if !staged && bs.canUseRenameForUpload { err := os.Rename(source, tempName) switch { case err == nil: @@ -80,7 +83,7 @@ func (bs *Blobstore) Upload(n *node.Node, source, copyTarget string) error { } } - if !bs.canUseRenameForUpload { + if !staged && !bs.canUseRenameForUpload { sourceFile, err := os.Open(source) if err != nil { return fmt.Errorf("failed to open source file '%s': %v", source, err) @@ -193,7 +196,12 @@ func (bs *Blobstore) UploadFromReader(n *node.Node, r io.Reader, size int64) err if n.SpaceRoot == nil { return errors.New("node has no space root") } - f, err := os.CreateTemp(n.SpaceRoot.InternalPath(), ".upload-*") + // stage in the space's tmp dir, which the watcher ignores + tmpDir := filepath.Join(n.SpaceRoot.InternalPath(), TMPDir) + if err := os.MkdirAll(tmpDir, 0700); err != nil { + return err + } + f, err := os.CreateTemp(tmpDir, ".upload-*") if err != nil { return errors.Wrap(err, "could not create temporary upload file") } diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/posix/posix.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/posix/posix.go index 3588b93719..3b66505a70 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/posix/posix.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/posix/posix.go @@ -28,9 +28,7 @@ import ( provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" "github.com/rs/zerolog" - tusd "github.com/tus/tusd/v2/pkg/handler" - "github.com/opencloud-eu/reva/v2/pkg/errtypes" "github.com/opencloud-eu/reva/v2/pkg/events" "github.com/opencloud-eu/reva/v2/pkg/rgrpc/todo/pool" "github.com/opencloud-eu/reva/v2/pkg/storage" @@ -49,7 +47,6 @@ import ( "github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/metadata/prefixes" "github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/node" "github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/permissions" - "github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/upload" "github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/usermapper" "github.com/opencloud-eu/reva/v2/pkg/storage/utils/middleware" "github.com/pkg/errors" @@ -74,6 +71,11 @@ func NewDefault(m map[string]interface{}, stream events.Stream, log *zerolog.Log return nil, err } + // Check this before connecting, otherwise a non-nats store keeps us retrying for minutes + if err := checkIDCacheStore(o); err != nil { + return nil, err + } + o.IDCache.Database += "_v2" // Use a versioned bucket name to avoid conflicts with previous implementations o.IDCache.TTL = 0 // Disable TTL for the ID cache, as the posix driver relies on it for caching file IDs and we don't want them to expire kv, err := cache.NewNatsKeyValue(o.IDCache, log) @@ -99,9 +101,16 @@ func NewDefault(m map[string]interface{}, stream events.Stream, log *zerolog.Log return New(o, stream, c, historyCache, log) } -func New(o *options.Options, stream events.Stream, cache, historyCache *idcache.IDCache, log *zerolog.Logger) (storage.FS, error) { +func checkIDCacheStore(o *options.Options) error { if o.IDCache.Store != "nats-js-kv" { - return nil, fmt.Errorf("the posix driver requires a nats-js-kv cache") + return fmt.Errorf("the posix driver requires a nats-js-kv id cache, got '%s'", o.IDCache.Store) + } + return nil +} + +func New(o *options.Options, stream events.Stream, cache, historyCache *idcache.IDCache, log *zerolog.Logger) (storage.FS, error) { + if err := checkIDCacheStore(o); err != nil { + return nil, err } if o.FileMetadataCache.Store == "noop" { return nil, fmt.Errorf("the posix driver requires a file metadata cache") @@ -179,13 +188,12 @@ func New(o *options.Options, stream events.Stream, cache, historyCache *idcache. } aspects := aspects.Aspects{ - Lookup: lu, - Tree: tp, - Permissions: p, - EventStream: stream, - UserMapper: um, - DisableVersioning: o.DisableVersioning, - Trashbin: trashbin, + Lookup: lu, + Tree: tp, + Permissions: p, + EventStream: stream, + UserMapper: um, + Trashbin: trashbin, } dfs, err := decomposedfs.New(&o.Options, aspects, log) @@ -245,54 +253,14 @@ func (fs *posixFS) WarmupIDCache(root string, assimilate, onlyDirty bool) error return fs.tree.WarmupIDCache(root, assimilate, onlyDirty) } -// ListUploadSessions returns the upload sessions matching the given filter -func (fs *posixFS) ListUploadSessions(ctx context.Context, filter storage.UploadSessionFilter) ([]storage.UploadSession, error) { - return fs.FS.(storage.UploadSessionLister).ListUploadSessions(ctx, filter) +// PrepareCreatesNode reports whether the wrapped driver's PrepareUpload creates a +// new file's node. +func (fs *posixFS) PrepareCreatesNode() bool { + nc, ok := fs.FS.(storage.NodeCreator) + return ok && nc.PrepareCreatesNode() } -// ResolveUpload resolves a finished upload to the resource it produced, read as the upload's -// executant. It is best effort: if the wrapped storage does not resolve uploads it returns -// NotSupported rather than panicking, so the tus finalize falls back to no headers. -func (fs *posixFS) ResolveUpload(ctx context.Context, info tusd.FileInfo) (*provider.ResourceInfo, context.Context, error) { - r, ok := fs.FS.(storage.UploadSessionResolver) - if !ok { - return nil, ctx, errtypes.NotSupported("storage does not resolve upload sessions") - } - return r.ResolveUpload(ctx, info) -} - -// UseIn tells the tus upload middleware which extensions it supports. -func (fs *posixFS) UseIn(composer *tusd.StoreComposer) { - fs.FS.(storage.ComposableFS).UseIn(composer) -} - -// NewUpload returns a new tus Upload instance -func (fs *posixFS) NewUpload(ctx context.Context, info tusd.FileInfo) (upload tusd.Upload, err error) { - return fs.FS.(tusd.DataStore).NewUpload(ctx, info) -} - -// NewUpload returns a new tus Upload instance -func (fs *posixFS) GetUpload(ctx context.Context, id string) (upload tusd.Upload, err error) { - return fs.FS.(tusd.DataStore).GetUpload(ctx, id) -} - -// AsTerminatableUpload returns a TerminatableUpload -// To implement the termination extension as specified in https://tus.io/protocols/resumable-upload.html#termination -// the storage needs to implement AsTerminatableUpload -func (fs *posixFS) AsTerminatableUpload(up tusd.Upload) tusd.TerminatableUpload { - return up.(*upload.DecomposedFsSession) -} - -// AsLengthDeclarableUpload returns a LengthDeclarableUpload -// To implement the creation-defer-length extension as specified in https://tus.io/protocols/resumable-upload.html#creation -// the storage needs to implement AsLengthDeclarableUpload -func (fs *posixFS) AsLengthDeclarableUpload(up tusd.Upload) tusd.LengthDeclarableUpload { - return up.(*upload.DecomposedFsSession) -} - -// AsConcatableUpload returns a ConcatableUpload -// To implement the concatenation extension as specified in https://tus.io/protocols/resumable-upload.html#concatenation -// the storage needs to implement AsConcatableUpload -func (fs *posixFS) AsConcatableUpload(up tusd.Upload) tusd.ConcatableUpload { - return up.(*upload.DecomposedFsSession) +// IsOrphaned reports whether the referenced resource exists but its metadata is unreadable. +func (fs *posixFS) IsOrphaned(ctx context.Context, ref *provider.Reference) bool { + return fs.FS.(storage.OrphanChecker).IsOrphaned(ctx, ref) } diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/posix/tree/tree.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/posix/tree/tree.go index 072c96a9b7..a2217ada15 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/posix/tree/tree.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/posix/tree/tree.go @@ -41,8 +41,10 @@ import ( provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" + "github.com/opencloud-eu/reva/v2/pkg/appctx" "github.com/opencloud-eu/reva/v2/pkg/errtypes" "github.com/opencloud-eu/reva/v2/pkg/events" + "github.com/opencloud-eu/reva/v2/pkg/storage" "github.com/opencloud-eu/reva/v2/pkg/storage/fs/posix/idcache" "github.com/opencloud-eu/reva/v2/pkg/storage/fs/posix/ignore" "github.com/opencloud-eu/reva/v2/pkg/storage/fs/posix/lookup" @@ -414,6 +416,9 @@ func (t *Tree) TouchFile(ctx context.Context, n *node.Node, markprocessing bool, return err } + if storage.SkipTouchPropagation(ctx) { + return nil + } return t.Propagate(ctx, n, 0) } @@ -788,8 +793,12 @@ func (t *Tree) InitNewNode(ctx context.Context, n *node.Node, fsize uint64) (met _, span := tracer.Start(ctx, "InitNewNode") defer span.End() + + // the node may not be cached yet, so its path comes from the parent and the name + nodePath := filepath.Join(n.ParentPath(), n.Name) + // create folder structure (if needed) - if err := os.MkdirAll(filepath.Dir(n.InternalPath()), 0700); err != nil { + if err := os.MkdirAll(filepath.Dir(nodePath), 0700); err != nil { return nil, err } @@ -800,36 +809,63 @@ func (t *Tree) InitNewNode(ctx context.Context, n *node.Node, fsize uint64) (met } // we also need to touch the actual node file here it stores the mtime of the resource - h, err := os.OpenFile(n.InternalPath(), os.O_CREATE|os.O_EXCL, 0600) + h, err := os.OpenFile(nodePath, os.O_CREATE|os.O_EXCL, 0600) if err != nil { + // the file is not ours: leave it, and its cache entry, alone + releaseNewNodeLock(ctx, n, unlock) if os.IsExist(err) { - return unlock, errtypes.AlreadyExists(n.InternalPath()) + // the name only: the message reaches the client, the path is the server's + return nil, errtypes.AlreadyExists(n.Name) } - return unlock, err + return nil, err + } + defer func() { _ = h.Close() }() + + // from here the file is ours. A failure removes it and our cache entry before + // unlocking, so nothing can open the node in between. + fail := func(err error) (metadata.UnlockFunc, error) { + if rErr := os.Remove(nodePath); rErr != nil { + t.log.Error().Err(rErr).Str("nodeid", n.ID).Msg("could not remove new node file") + } + if dErr := t.lookup.IDCache.Delete(ctx, n.SpaceID, n.ID); dErr != nil { + t.log.Error().Err(dErr).Str("nodeid", n.ID).Msg("could not remove new node from the id cache") + } + releaseNewNodeLock(ctx, n, unlock) + return nil, err + } + + // cached only now that the name is ours, so a losing upload cannot point it at its id + if err := t.lookup.CacheID(ctx, n.SpaceID, n.ID, nodePath); err != nil { + return fail(err) } // Set known mtime from filesystem to metadata to preven re-assimilation fi, err := h.Stat() if err != nil { - return nil, err + return fail(err) } mtime := fi.ModTime() err = n.SetXattrsWithContext(ctx, map[string][]byte{ prefixes.MTimeAttr: []byte(mtime.UTC().Format(time.RFC3339Nano)), }) if err != nil { - t.log.Error().Err(err).Str("path", n.InternalPath()).Msg("could not set mtime attribute on new node") + t.log.Error().Err(err).Str("path", nodePath).Msg("could not set mtime attribute on new node") } - _ = h.Close() - if _, err := node.CheckQuota(ctx, n.SpaceRoot, false, 0, fsize); err != nil { - return unlock, err + return fail(err) } return unlock, nil } +// releaseNewNodeLock releases the lock of a node InitNewNode failed to create. +func releaseNewNodeLock(ctx context.Context, n *node.Node, unlock metadata.UnlockFunc) { + if err := unlock(); err != nil { + appctx.GetLogger(ctx).Error().Err(err).Str("nodeid", n.ID).Msg("could not release new node lock") + } +} + // TODO check if node exists? func (t *Tree) createDirNode(ctx context.Context, n *node.Node) (err error) { if t.Ignorer.IsIgnored(filepath.Join(n.ParentPath(), n.Name)) { diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/aspects/aspects.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/aspects/aspects.go index 69ebcc93f9..4153f8ed68 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/aspects/aspects.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/aspects/aspects.go @@ -28,11 +28,13 @@ import ( // Aspects holds dependencies for handling aspects of the decomposedfs type Aspects struct { - Lookup node.PathLookup - Tree node.Tree - Trashbin trashbin.Trashbin - Permissions permissions.Permissions - EventStream events.Stream - DisableVersioning bool - UserMapper usermapper.Mapper + Lookup node.PathLookup + Tree node.Tree + Trashbin trashbin.Trashbin + Permissions permissions.Permissions + EventStream events.Stream + UserMapper usermapper.Mapper + // SeparateBlobs is set when the blobstore keeps blobs apart from the nodes, + // so a blob can be stored before any node references it. + SeparateBlobs bool } diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/commit_upload.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/commit_upload.go index 462889799d..d0d744d98e 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/commit_upload.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/commit_upload.go @@ -19,6 +19,8 @@ package decomposedfs import ( "context" + "path/filepath" + "strings" "time" provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" @@ -27,6 +29,7 @@ import ( "github.com/opencloud-eu/reva/v2/pkg/appctx" "github.com/opencloud-eu/reva/v2/pkg/errtypes" "github.com/opencloud-eu/reva/v2/pkg/storage" + "github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/metadata" "github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/metadata/prefixes" "github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/node" ) @@ -62,20 +65,24 @@ func (fs *Decomposedfs) MarkProcessing(ctx context.Context, ref *provider.Refere return n.RemoveXattr(ctx, prefixes.StatusPrefix) } - if n.IsProcessing(ctx) { - return errtypes.ResourceProcessing(ref.String()) - } + // a newer upload takes over the mark, the last writer wins return n.SetXattrsWithContext(ctx, node.Attributes{ prefixes.StatusPrefix: []byte(node.ProcessingStatus + sessionID), }) } // CommitUpload writes the staged bytes from source to the resource at ref. -// sessionID is used to identify the correct blob slot prepared before postprocessing. +// sessionID identifies the upload that PrepareUpload wrote onto the node. // Caller owns source.Body and must close it after CommitUpload returns. +// +// The bytes are written against the real node, so drivers that keep the content +// in the node itself (posix) can replace it atomically. If a newer upload took +// over the node in the meantime, the bytes go to the revision that upload created +// for this session instead. Without such a revision (versioning disabled) they are +// discarded: nothing references them anymore. func (fs *Decomposedfs) CommitUpload(ctx context.Context, ref *provider.Reference, sessionID string, source storage.UploadSource) error { - if source.Body == nil { - return errtypes.BadRequest("Decomposedfs: source body is nil") + if source.Body == nil && source.Path == "" { + return errtypes.BadRequest("Decomposedfs: source has neither body nor path") } if sessionID == "" { return errtypes.BadRequest("Decomposedfs: sessionID is empty") @@ -89,17 +96,75 @@ func (fs *Decomposedfs) CommitUpload(ctx context.Context, ref *provider.Referenc if !n.Exists { return errtypes.NotFound(ref.String()) } + n.SpaceRoot, err = node.ReadNode(ctx, fs.lu, n.SpaceID, n.SpaceID, "", false, nil, false) + if err != nil { + return err + } - blobNode := node.New(n.SpaceID, n.ID, "", "", source.Length, sessionID, - provider.ResourceType_RESOURCE_TYPE_FILE, nil, fs.lu) + unlock, err := fs.lu.MetadataBackend().Lock(n) + if err != nil { + return errors.Wrap(err, "Decomposedfs: could not lock node") + } + defer func() { + _ = unlock() + }() - if err := fs.tp.WriteBlobFromReader(blobNode, source.Body, source.Length); err != nil { - if derr := fs.tp.DeleteBlob(blobNode); derr != nil { + // re-read the blob id while holding the lock, a newer upload may have taken over. + // read the attribute itself: the posix lookup's ReadBlobIDAndSizeAttr reports no blob id + blobID, err := fs.lu.MetadataBackend().Get(ctx, n, prefixes.BlobIDAttr) + if err != nil { + return errors.Wrap(err, "Decomposedfs: could not read blob id") + } + n.BlobID = string(blobID) + + target := n + if n.BlobID != sessionID { + revision, revisionUnlock, err := fs.uploadRevision(ctx, n, sessionID) + if err != nil { + return err + } + if revision == nil { + appctx.GetLogger(ctx).Info().Str("nodeid", n.ID).Str("sessionid", sessionID).Msg("upload was superseded and has no revision, discarding its bytes") + return nil + } + defer func() { + _ = revisionUnlock() + }() + target = revision + } + + if source.Path != "" { + err = fs.tp.WriteBlob(target, source.Path) + } else { + err = fs.tp.WriteBlobFromReader(target, source.Body, source.Length) + } + if err != nil { + if derr := fs.tp.DeleteBlob(target); derr != nil { appctx.GetLogger(ctx).Error().Err(derr).Str("nodeid", n.ID).Str("blobid", sessionID).Msg("could not clean up orphaned blob after failed write") } return errors.Wrap(err, "Decomposedfs: failed to write blob") } + // on the node that holds the content, not the session: the session is deleted when the + // upload finishes + if !source.ScanDate.IsZero() { + if err := target.SetScanData(ctx, source.ScanResult, source.ScanDate); err != nil { + appctx.GetLogger(ctx).Error().Err(err).Str("nodeid", target.ID).Msg("could not set scan results") + } + } + + if target != n { + // the revision kept this upload's processing mark for a rollback of the newer + // upload; this upload is done, so restoring it must not mark the node again + if err := target.RemoveXattr(ctx, prefixes.StatusPrefix); err != nil && !metadata.IsAttrUnset(err) { + appctx.GetLogger(ctx).Error().Err(err).Str("nodeid", target.ID).Msg("could not remove the processing mark from the revision") + } + } else { + // revisions kept only for a rollback of this upload served their purpose; versions + // stay, also the ones created before versioning was disabled + fs.removeRevisions(ctx, n) + } + now := time.Now() if p, err := n.Parent(ctx); err != nil { appctx.GetLogger(ctx).Error().Err(err).Str("nodeid", n.ID).Msg("could not read parent for etag propagation") @@ -112,3 +177,72 @@ func (fs *Decomposedfs) CommitUpload(ctx context.Context, ref *provider.Referenc return nil } + +// removeRevisions deletes the revisions of n that were kept only for a rollback, with their +// blobs, while the caller holds the node lock: the ones of uploads that were rolled back, +// and the snapshots taken with versioning disabled. +func (fs *Decomposedfs) removeRevisions(ctx context.Context, n *node.Node) { + revPrefix := fs.lu.VersionPath(n.SpaceID, n.ID, "") + revisions, err := filepath.Glob(fs.lu.VersionPath(n.SpaceID, n.ID, "*")) + if err != nil { + appctx.GetLogger(ctx).Error().Err(err).Str("nodeid", n.ID).Msg("could not list revisions") + return + } + for _, rev := range revisions { + if strings.HasSuffix(rev, ".mpk") || strings.HasSuffix(rev, ".mlock") { + continue + } + revisionNode := node.NewBaseNode(n.SpaceID, n.ID+node.RevisionIDDelimiter+strings.TrimPrefix(rev, revPrefix), fs.lu) + if !fs.keptForRollback(ctx, revisionNode) { + continue + } + blobID, err := fs.lu.MetadataBackend().Get(ctx, revisionNode, prefixes.BlobIDAttr) + if err == nil && len(blobID) > 0 && string(blobID) != n.BlobID { + blobNode := node.New(n.SpaceID, revisionNode.ID, "", "", 0, string(blobID), provider.ResourceType_RESOURCE_TYPE_FILE, nil, fs.lu) + if err := fs.tp.DeleteBlob(blobNode); err != nil { + appctx.GetLogger(ctx).Error().Err(err).Str("revisionid", revisionNode.ID).Msg("could not delete the blob of a superseded revision") + } + } + removeRevision(ctx, fs.lu, revisionNode) + } +} + +// keptForRollback reports whether a revision exists only for a rollback, rather than as a +// version. +func (fs *Decomposedfs) keptForRollback(ctx context.Context, revision metadata.MetadataNode) bool { + for _, attr := range []string{purgeOnRestoreAttr, uploadSnapshotAttr} { + if _, err := fs.lu.MetadataBackend().Get(ctx, revision, attr); err == nil { + return true + } + } + return false +} + +// uploadRevision returns the locked revision of n that holds the upload sessionID, +// or nil if there is none. +func (fs *Decomposedfs) uploadRevision(ctx context.Context, n *node.Node, sessionID string) (*node.Node, metadata.UnlockFunc, error) { + revPrefix := fs.lu.VersionPath(n.SpaceID, n.ID, "") + revisions, err := filepath.Glob(fs.lu.VersionPath(n.SpaceID, n.ID, "*")) + if err != nil { + return nil, nil, err + } + for _, rev := range revisions { + if strings.HasSuffix(rev, ".mpk") || strings.HasSuffix(rev, ".mlock") { + continue + } + revisionID := n.ID + node.RevisionIDDelimiter + strings.TrimPrefix(rev, revPrefix) + blobID, err := fs.lu.MetadataBackend().Get(ctx, node.NewBaseNode(n.SpaceID, revisionID, fs.lu), prefixes.BlobIDAttr) + if err != nil || string(blobID) != sessionID { + continue + } + revision, unlock, err := node.LockAndReadNode(ctx, fs.lu, n.SpaceID, revisionID, "", false, n.SpaceRoot, false) + if err != nil { + return nil, nil, err + } + // ReadNode caches the attributes of the node, not of the revision. The posix + // blobstore copies them onto the file it writes, so read the revision's own. + revision.ResetXattrsCache() + return revision, unlock, nil + } + return nil, nil, nil +} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/decomposedfs.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/decomposedfs.go index 557046958a..5c772f996b 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/decomposedfs.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/decomposedfs.go @@ -36,7 +36,6 @@ import ( "github.com/jellydator/ttlcache/v2" "github.com/pkg/errors" "github.com/rs/zerolog" - tusd "github.com/tus/tusd/v2/pkg/handler" microstore "go-micro.dev/v4/store" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/trace" @@ -48,7 +47,6 @@ import ( "github.com/opencloud-eu/reva/v2/pkg/errtypes" "github.com/opencloud-eu/reva/v2/pkg/events" "github.com/opencloud-eu/reva/v2/pkg/rgrpc/todo/pool" - "github.com/opencloud-eu/reva/v2/pkg/rhttp/datatx/metrics" "github.com/opencloud-eu/reva/v2/pkg/storage" "github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/aspects" "github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/lookup" @@ -61,9 +59,7 @@ import ( "github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/timemanager" "github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/trashbin" "github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/tree" - "github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/upload" "github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/usermapper" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/chunking" "github.com/opencloud-eu/reva/v2/pkg/storage/utils/filelocks" "github.com/opencloud-eu/reva/v2/pkg/storage/utils/templates" "github.com/opencloud-eu/reva/v2/pkg/storagespace" @@ -81,11 +77,6 @@ var ( tracer trace.Tracer _registeredEvents = []events.Unmarshaller{ - events.PostprocessingFinished{}, - events.PostprocessingStepFinished{}, - events.RestartPostprocessing{}, - events.StartPostprocessingStep{}, - events.CleanUpload{}, events.DeleteRevision{}, } ) @@ -94,41 +85,21 @@ func init() { tracer = otel.Tracer("github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs") } -// Session is the interface that DecomposedfsSession implements. By combining tus.Upload, -// storage.UploadSession and custom functions we can reuse the same struct throughout -// the whole upload lifecycle. -// -// Some functions that are only used by decomposedfs are not yet part of this interface. -// They might be added after more refactoring. -type Session interface { - tusd.Upload - storage.UploadSession - upload.Session - LockID() string -} - type IDCachingTree interface { WarmupIDCache(root string, assimilate, onlyDirty bool) error } -type SessionStore interface { - New(ctx context.Context) *upload.DecomposedFsSession - SessionFromInfo(info tusd.FileInfo) *upload.DecomposedFsSession - List(ctx context.Context) ([]*upload.DecomposedFsSession, error) - Get(ctx context.Context, id string) (*upload.DecomposedFsSession, error) -} - // Decomposedfs provides the base for decomposed filesystem implementations type Decomposedfs struct { - lu node.PathLookup - tp node.Tree - trashbin trashbin.Trashbin - o *options.Options - p permissions.Permissions - um usermapper.Mapper - chunkHandler *chunking.ChunkHandler - stream events.Stream - sessionStore SessionStore + lu node.PathLookup + tp node.Tree + trashbin trashbin.Trashbin + o *options.Options + p permissions.Permissions + um usermapper.Mapper + stream events.Stream + // separateBlobs is set when the blobstore keeps blobs apart from the nodes + separateBlobs bool UserCache *ttlcache.Cache userSpaceIndex *spaceidindex.Index @@ -185,12 +156,12 @@ func NewDefault(m map[string]interface{}, bs node.Blobstore, es events.Stream, l ), log) aspects := aspects.Aspects{ - Lookup: lu, - Tree: tp, - Permissions: p, - EventStream: es, - DisableVersioning: o.DisableVersioning, - Trashbin: &DecomposedfsTrashbin{}, + Lookup: lu, + Tree: tp, + Permissions: p, + EventStream: es, + Trashbin: &DecomposedfsTrashbin{}, + SeparateBlobs: true, } return New(o, aspects, log) @@ -252,8 +223,8 @@ func New(o *options.Options, aspects aspects.Aspects, log *zerolog.Logger) (stor o: o, p: aspects.Permissions, um: aspects.UserMapper, - chunkHandler: chunking.NewChunkHandler(filepath.Join(o.Root, "uploads")), stream: aspects.EventStream, + separateBlobs: aspects.SeparateBlobs, UserCache: ttlcache.NewCache(), userSpaceIndex: userSpaceIndex, groupSpaceIndex: groupSpaceIndex, @@ -261,7 +232,6 @@ func New(o *options.Options, aspects aspects.Aspects, log *zerolog.Logger) (stor spaceTypeIndex: spaceTypeIndex, log: log, } - fs.sessionStore = upload.NewSessionStore(fs, aspects, o.Root, o.AsyncFileUploads, o.Tokens, log) if err = fs.trashbin.Setup(fs); err != nil { return nil, err } @@ -272,7 +242,9 @@ func New(o *options.Options, aspects aspects.Aspects, log *zerolog.Logger) (stor return nil, errors.New("need nats for async file processing") } - ch, err := events.Consume(fs.stream, "dcfs", _registeredEvents...) + // a group of its own: the upload coordinator holds the "dcfs" group, and one + // group gets one copy of each event + ch, err := events.Consume(fs.stream, "dcfs-revisions", _registeredEvents...) if err != nil { return nil, err } @@ -282,201 +254,32 @@ func New(o *options.Options, aspects aspects.Aspects, log *zerolog.Logger) (stor } for i := 0; i < o.Events.NumConsumers; i++ { - go fs.Postprocessing(ch) + go fs.ConsumeRevisionEvents(ch) } } return fs, nil } -// Postprocessing starts the postprocessing result collector -func (fs *Decomposedfs) Postprocessing(ch <-chan events.Event) { +// ConsumeRevisionEvents starts the revision event collector. Upload postprocessing +// results are consumed by the upload coordinator. +func (fs *Decomposedfs) ConsumeRevisionEvents(ch <-chan events.Event) { for event := range ch { // derive a per-event context from the event's W3C trace context so the - // postprocessing work is linked to the originating request + // work is linked to the originating request ctx := event.GetTraceContext(context.Background()) ctx = ctxpkg.ContextSetInitiator(ctx, event.InitiatorID) - fs.handlePostprocessingEvent(ctx, event) + fs.handleRevisionEvent(ctx, event) } } -// handlePostprocessingEvent processes a single postprocessing event under a span -// scoped to that event's trace context. -func (fs *Decomposedfs) handlePostprocessingEvent(ctx context.Context, event events.Event) { - ctx, span := tracer.Start(ctx, "Postprocessing/"+event.Type) +// handleRevisionEvent processes a single revision event under a span scoped to +// that event's trace context. +func (fs *Decomposedfs) handleRevisionEvent(ctx context.Context, event events.Event) { + ctx, span := tracer.Start(ctx, "ConsumeRevisionEvents/"+event.Type) defer span.End() log := fs.log switch ev := event.Event.(type) { - case events.PostprocessingFinished: - sublog := log.With().Str("event", "PostprocessingFinished").Str("uploadid", ev.UploadID).Logger() - session, err := fs.sessionStore.Get(ctx, ev.UploadID) - if err != nil { - sublog.Error().Err(err).Msg("Failed to get upload") - return // NOTE: since we can't get the upload, we can't delete the blob - } - - n, err := session.Node(ctx) - if err != nil { - sublog.Error().Err(err).Msg("could not read node") - return - } - sublog = log.With().Str("spaceid", session.SpaceID()).Str("nodeid", session.NodeID()).Logger() - if !n.Exists { - sublog.Debug().Msg("node no longer exists") - session.Cleanup(false, true, true, false) - return - } - - var ( - failed bool - revertNodeMetadata bool - keepUpload bool - ) - unmarkPostprocessing := true - - switch ev.Outcome { - default: - sublog.Error().Str("outcome", string(ev.Outcome)).Msg("unknown postprocessing outcome - aborting") - fallthrough - case events.PPOutcomeAbort: - failed = true - revertNodeMetadata = true - keepUpload = true - metrics.UploadSessionsAborted.Inc() - case events.PPOutcomeContinue: - if err := session.Finalize(ctx); err != nil { - sublog.Error().Err(err).Msg("could not finalize upload") - failed = true - revertNodeMetadata = false - keepUpload = true - // keep postprocessing status so the upload is not deleted during housekeeping - unmarkPostprocessing = false - } else { - metrics.UploadSessionsFinalized.Inc() - } - case events.PPOutcomeDelete: - failed = true - revertNodeMetadata = true - metrics.UploadSessionsDeleted.Inc() - } - - getParent := func() *node.Node { - p, err := n.Parent(ctx) - if err != nil { - sublog.Error().Err(err).Msg("could not read parent") - return nil - } - return p - } - - now := time.Now() - var parentId *provider.ResourceId - if failed { - // if no other upload session is in progress (processing id != session id) or has finished (processing id == "") - latestSession, err := n.ProcessingID(ctx) - if err != nil { - sublog.Error().Err(err).Msg("reading node for session failed") - } - if latestSession == session.ID() { - // propagate reverted sizeDiff after failed postprocessing - if err := fs.tp.Propagate(ctx, n, -session.SizeDiff()); err != nil { - sublog.Error().Err(err).Msg("could not propagate tree size change") - } - } - } else if p := getParent(); p != nil { - parentId = &provider.ResourceId{ - StorageId: session.ProviderID(), - SpaceId: session.SpaceID(), - OpaqueId: p.ID, - } - // update parent tmtime to propagate etag change after successful postprocessing - _ = p.SetTMTime(ctx, &now) - if err := fs.tp.Propagate(ctx, p, 0); err != nil { - sublog.Error().Err(err).Msg("could not propagate etag change") - } - } - - session.Cleanup(revertNodeMetadata, !keepUpload, !keepUpload, unmarkPostprocessing) - - var isVersion bool - if session.NodeExists() { - info, err := session.GetInfo(ctx) - if err == nil && info.MetaData["versionID"] != "" { - isVersion = true - } - } - - if err := events.Publish( - ctx, - fs.stream, - events.UploadReady{ - UploadID: ev.UploadID, - Failed: failed, - ExecutingUser: ev.ExecutingUser, - Filename: ev.Filename, - FileRef: &provider.Reference{ - ResourceId: &provider.ResourceId{ - StorageId: session.ProviderID(), - SpaceId: session.SpaceID(), - OpaqueId: session.SpaceID(), - }, - Path: utils.MakeRelativePath(filepath.Join(session.Dir(), session.Filename())), - }, - ResourceID: &provider.ResourceId{ - StorageId: session.ProviderID(), - SpaceId: session.SpaceID(), - OpaqueId: session.NodeID(), - }, - ParentID: parentId, - Timestamp: utils.TimeToTS(now), - SpaceOwner: n.SpaceOwnerOrManager(ctx), - IsVersion: isVersion, - ImpersonatingUser: ev.ImpersonatingUser, - }, - ); err != nil { - sublog.Error().Err(err).Msg("Failed to publish UploadReady event") - } - case events.RestartPostprocessing: - sublog := log.With().Str("event", "RestartPostprocessing").Str("uploadid", ev.UploadID).Logger() - session, err := fs.sessionStore.Get(ctx, ev.UploadID) - if err != nil { - sublog.Error().Err(err).Msg("Failed to get upload") - return - } - n, err := session.Node(ctx) - if err != nil { - sublog.Error().Err(err).Msg("could not read node") - return - } - sublog = log.With().Str("spaceid", session.SpaceID()).Str("nodeid", session.NodeID()).Logger() - s, err := session.URL(ctx) - if err != nil { - sublog.Error().Err(err).Msg("could not create url") - return - } - - metrics.UploadSessionsRestarted.Inc() - - // restart postprocessing - if err := events.Publish(ctx, fs.stream, events.BytesReceived{ - UploadID: session.ID(), - URL: s, - SpaceOwner: n.SpaceOwnerOrManager(ctx), - ExecutingUser: &user.User{Id: &user.UserId{OpaqueId: "postprocessing-restart"}}, // send nil instead? - ResourceID: &provider.ResourceId{SpaceId: n.SpaceID, OpaqueId: n.ID}, - Filename: session.Filename(), - Filesize: uint64(session.Size()), - }); err != nil { - sublog.Error().Err(err).Msg("Failed to publish BytesReceived event") - } - case events.CleanUpload: - sublog := log.With().Str("event", "CleanUpload").Str("uploadid", ev.UploadID).Logger() - session, err := fs.sessionStore.Get(ctx, ev.UploadID) - if err != nil { - sublog.Error().Err(err).Msg("Failed to get upload") - return // NOTE: since we can't get the upload, we can't delete the blob - } - session.Cleanup(true, !ev.KeepUpload, !ev.KeepUpload, true) case events.DeleteRevision: sublog := log.With().Str("event", "DeleteRevision").Interface("nodeid", ev.ResourceID).Logger() n, err := fs.lu.NodeFromID(ctx, ev.ResourceID) @@ -502,152 +305,6 @@ func (fs *Decomposedfs) handlePostprocessingEvent(ctx context.Context, event eve if deleteErr != nil { sublog.Error().Err(deleteErr).Msg("Failed to delete revision") } - case events.StartPostprocessingStep: - sublog := log.With().Str("event", "StartPostprocessingStep").Str("uploadid", ev.UploadID).Logger() - if ev.UploadID == "" { - sublog.Error().Msg("UploadID is empty, cannot start postprocessing step") - return - } - session, err := fs.sessionStore.Get(ctx, ev.UploadID) - if err != nil { - sublog.Error().Err(err).Msg("Failed to get upload") - return - } - session.SetStatus(upload.SessionStatusProcessing, "started postprocessing step: "+string(ev.StepToStart)) - err = session.Persist(ctx) - if err != nil { - sublog.Error().Err(err).Msg("Failed to persist upload session after starting postprocessing step") - } - case events.PostprocessingStepFinished: - sublog := log.With().Str("event", "PostprocessingStepFinished").Str("uploadid", ev.UploadID).Logger() - if ev.FinishedStep != events.PPStepAntivirus { - // atm we are only interested in antivirus results - return - } - - res := ev.Result.(events.VirusscanResult) - if res.ErrorMsg != "" { - // scan failed somehow - // Should we handle this here? - return - } - sublog = log.With().Str("scan_description", res.Description).Bool("infected", res.Infected).Logger() - - var n *node.Node - switch ev.UploadID { - case "": - // uploadid is empty -> this was an on-demand scan - /* ON DEMAND SCANNING NOT SUPPORTED ATM - ctx := ctxpkg.ContextSetUser(context.Background(), ev.ExecutingUser) - ref := &provider.Reference{ResourceId: ev.ResourceID} - - no, err := fs.lu.NodeFromResource(ctx, ref) - if err != nil { - log.Error().Err(err).Interface("resourceID", ev.ResourceID).Msg("Failed to get node after scan") - continue - - } - n = no - if ev.Outcome == events.PPOutcomeDelete { - // antivir wants us to delete the file. We must obey and need to - - // check if there a previous versions existing - revs, err := fs.ListRevisions(ctx, ref) - if len(revs) == 0 { - if err != nil { - log.Error().Err(err).Interface("resourceID", ev.ResourceID).Msg("Failed to list revisions. Fallback to delete file") - } - - // no versions -> trash file - err := fs.Delete(ctx, ref) - if err != nil { - log.Error().Err(err).Interface("resourceID", ev.ResourceID).Msg("Failed to delete infected resource") - continue - } - - // now purge it from the recycle bin - if err := fs.PurgeRecycleItem(ctx, &provider.Reference{ResourceId: &provider.ResourceId{SpaceId: n.SpaceID, OpaqueId: n.SpaceID}}, n.ID, "/"); err != nil { - log.Error().Err(err).Interface("resourceID", ev.ResourceID).Msg("Failed to purge infected resource from trash") - } - - // remove cache entry in gateway - fs.cache.RemoveStatContext(ctx, ev.ExecutingUser.GetId(), &provider.ResourceId{SpaceId: n.SpaceID, OpaqueId: n.ID}) - continue - } - - // we have versions - find the newest - versions := make(map[uint64]string) // remember all versions - we need them later - var nv uint64 - for _, v := range revs { - versions[v.Mtime] = v.Key - if v.Mtime > nv { - nv = v.Mtime - } - } - - // restore newest version - if err := fs.RestoreRevision(ctx, ref, versions[nv]); err != nil { - log.Error().Err(err).Interface("resourceID", ev.ResourceID).Str("revision", versions[nv]).Msg("Failed to restore revision") - continue - } - - // now find infected version - revs, err = fs.ListRevisions(ctx, ref) - if err != nil { - log.Error().Err(err).Interface("resourceID", ev.ResourceID).Msg("Error listing revisions after restore") - } - - for _, v := range revs { - // we looking for a version that was previously not there - if _, ok := versions[v.Mtime]; ok { - continue - } - - if err := fs.DeleteRevision(ctx, ref, v.Key); err != nil { - log.Error().Err(err).Interface("resourceID", ev.ResourceID).Str("revision", v.Key).Msg("Failed to delete revision") - } - } - - // remove cache entry in gateway - fs.cache.RemoveStatContext(ctx, ev.ExecutingUser.GetId(), &provider.ResourceId{SpaceId: n.SpaceID, OpaqueId: n.ID}) - continue - } - */ - default: - // uploadid is not empty -> this is an async upload - session, err := fs.sessionStore.Get(ctx, ev.UploadID) - if err != nil { - sublog.Error().Err(err).Msg("Failed to get upload") - return - } - - n, err = session.Node(ctx) - if err != nil { - sublog.Error().Err(err).Msg("Failed to get node after scan") - return - } - sublog = log.With().Str("spaceid", session.SpaceID()).Str("nodeid", session.NodeID()).Logger() - - session.SetScanData(res.Description, res.Scandate) - var status string - switch ev.Outcome { - case events.PPOutcomeAbort, events.PPOutcomeDelete: - status = upload.SessionStatusFailed - default: - status = upload.SessionStatusProcessing - } - session.SetStatus(status, "finished postprocessing step: "+string(ev.FinishedStep)) - if err := session.Persist(ctx); err != nil { - sublog.Error().Err(err).Msg("Failed to persist scan results") - } - } - - if err := n.SetScanData(ctx, res.Description, res.Scandate); err != nil { - sublog.Error().Err(err).Msg("Failed to set scan results") - return - } - - metrics.UploadSessionsScanned.Inc() default: log.Error().Interface("event", ev).Msg("Unknown event") } @@ -665,6 +322,12 @@ func (fs *Decomposedfs) Shutdown(ctx context.Context) error { return nil } +// Capabilities declares decomposedfs fully writeable, stated explicitly so it is +// a decision here and not an inherited default. +func (fs *Decomposedfs) Capabilities(_ context.Context) storage.Capabilities { + return storage.FullCapabilities() +} + // GetQuota returns the quota available // TODO Document in the cs3 should we return quota or free space? func (fs *Decomposedfs) GetQuota(ctx context.Context, ref *provider.Reference) (total uint64, inUse uint64, remaining uint64, err error) { @@ -804,13 +467,13 @@ func (fs *Decomposedfs) GetPathByID(ctx context.Context, id *provider.ResourceId } // CreateDir creates the specified directory -func (fs *Decomposedfs) CreateDir(ctx context.Context, ref *provider.Reference) (err error) { +func (fs *Decomposedfs) CreateDir(ctx context.Context, ref *provider.Reference) (_ *storage.CreateDirResult, err error) { ctx, span := tracer.Start(ctx, "CreateDir") defer span.End() name := path.Base(ref.Path) if name == "" || name == "." || name == "/" { - return errtypes.BadRequest("Invalid path: " + ref.Path) + return nil, errtypes.BadRequest("Invalid path: " + ref.Path) } parentRef := &provider.Reference{ @@ -822,52 +485,51 @@ func (fs *Decomposedfs) CreateDir(ctx context.Context, ref *provider.Reference) var n *node.Node if n, err = fs.lu.NodeFromResource(ctx, parentRef); err != nil { if e, ok := err.(errtypes.NotFound); ok { - return errtypes.PreconditionFailed(e.Error()) + return nil, errtypes.PreconditionFailed(e.Error()) } - return + return nil, err } // TODO check if user has access to root / space if !n.Exists { - return errtypes.PreconditionFailed(parentRef.Path) + return nil, errtypes.PreconditionFailed(parentRef.Path) } rp, err := fs.p.AssemblePermissions(ctx, n) switch { case err != nil: - return err + return nil, err case !rp.CreateContainer: f, _ := storagespace.FormatReference(ref) if rp.Stat { - return errtypes.PermissionDenied(f) + return nil, errtypes.PermissionDenied(f) } - return errtypes.NotFound(f) + return nil, errtypes.NotFound(f) } - // Set space owner in context - storagespace.ContextSendSpaceOwnerID(ctx, n.SpaceOwnerOrManager(ctx)) + spaceOwner := n.SpaceOwnerOrManager(ctx) // check lock if err := n.CheckLock(ctx); err != nil { - return err + return nil, err } // verify child does not exist, yet if n, err = n.Child(ctx, name); err != nil { - return + return nil, err } if n.Exists { - return errtypes.AlreadyExists(ref.Path) + return nil, errtypes.AlreadyExists(ref.Path) } if err = fs.tp.CreateDir(ctx, n); err != nil { - return + return nil, err } - return + return &storage.CreateDirResult{SpaceOwner: spaceOwner, SpaceID: n.SpaceID, ResourceID: &provider.ResourceId{OpaqueId: n.ID, SpaceId: n.SpaceID}}, nil } // TouchFile as defined in the storage.FS interface -func (fs *Decomposedfs) TouchFile(ctx context.Context, ref *provider.Reference, markprocessing bool, mtime string) error { +func (fs *Decomposedfs) TouchFile(ctx context.Context, ref *provider.Reference, markprocessing bool, mtime string) (*storage.TouchFileResult, error) { ctx, span := tracer.Start(ctx, "TouchFile") defer span.End() parentRef := &provider.Reference{ @@ -878,15 +540,15 @@ func (fs *Decomposedfs) TouchFile(ctx context.Context, ref *provider.Reference, // verify parent exists parent, err := fs.lu.NodeFromResource(ctx, parentRef) if err != nil { - return errtypes.InternalError(err.Error()) + return nil, errtypes.InternalError(err.Error()) } if !parent.Exists { - return errtypes.NotFound(parentRef.Path) + return nil, errtypes.NotFound(parentRef.Path) } n, err := fs.lu.NodeFromResource(ctx, ref) if err != nil { - return errtypes.InternalError(err.Error()) + return nil, errtypes.InternalError(err.Error()) } // new file: check write permission on parent, not the not-yet-existing node @@ -897,23 +559,25 @@ func (fs *Decomposedfs) TouchFile(ctx context.Context, ref *provider.Reference, rp, err := fs.p.AssemblePermissions(ctx, permNode) switch { case err != nil: - return err + return nil, err case !rp.InitiateFileUpload: f, _ := storagespace.FormatReference(ref) if rp.Stat { - return errtypes.PermissionDenied(f) + return nil, errtypes.PermissionDenied(f) } - return errtypes.NotFound(f) + return nil, errtypes.NotFound(f) } - // Set space owner in context - storagespace.ContextSendSpaceOwnerID(ctx, n.SpaceOwnerOrManager(ctx)) + spaceOwner := n.SpaceOwnerOrManager(ctx) // check lock if err := n.CheckLock(ctx); err != nil { - return err + return nil, err } - return fs.tp.TouchFile(ctx, n, markprocessing, mtime) + if err := fs.tp.TouchFile(ctx, n, markprocessing, mtime); err != nil { + return nil, err + } + return &storage.TouchFileResult{SpaceOwner: spaceOwner, SpaceID: n.SpaceID, ResourceID: &provider.ResourceId{OpaqueId: n.ID, SpaceId: n.SpaceID}}, nil } // CreateReference creates a reference as a node folder with the target stored in extended attributes @@ -982,6 +646,9 @@ func (fs *Decomposedfs) Move(ctx context.Context, oldRef, newRef *provider.Refer return nil, errtypes.NotFound(f) } + // Set space owner in context + storagespace.ContextSetSpaceOwner(ctx, newNode.SpaceOwnerOrManager(ctx)) + // check lock on source if err := oldNode.CheckLock(ctx); err != nil { return nil, err @@ -1208,46 +875,56 @@ func (fs *Decomposedfs) RemoveLabel(ctx context.Context, ref *provider.Reference } // Delete deletes the specified resource -func (fs *Decomposedfs) Delete(ctx context.Context, ref *provider.Reference) (err error) { +func (fs *Decomposedfs) Delete(ctx context.Context, ref *provider.Reference) (dr *storage.DeleteResult, err error) { ctx, span := tracer.Start(ctx, "Delete") defer span.End() var node *node.Node if node, err = fs.lu.NodeFromResource(ctx, ref); err != nil { - return + return nil, err } if !node.Exists { - return errtypes.NotFound(filepath.Join(node.ParentID, node.Name)) + return nil, errtypes.NotFound(filepath.Join(node.ParentID, node.Name)) + } + + if node.IsProcessing(ctx) { + return nil, errtypes.TooEarly("file is processing") } rp, err := fs.p.AssemblePermissions(ctx, node) switch { case err != nil: - return err + return nil, err case !rp.Delete: f, _ := storagespace.FormatReference(ref) if rp.Stat { - return errtypes.PermissionDenied(f) + return nil, errtypes.PermissionDenied(f) } - return errtypes.NotFound(f) + return nil, errtypes.NotFound(f) } parentAllowsDelete := func(parentPerms *provider.ResourcePermissions) bool { return parentPerms.GetDelete() } if err := fs.checkParentPermission(ctx, node, ref, parentAllowsDelete); err != nil { - return err + return nil, err } - // Set space owner in context - storagespace.ContextSendSpaceOwnerID(ctx, node.SpaceOwnerOrManager(ctx)) - if err := node.CheckLock(ctx); err != nil { - return err + return nil, err } if node.IsProcessing(ctx) { - return errtypes.ResourceProcessing(ref.String()) + return nil, errtypes.ResourceProcessing(ref.String()) } - return fs.tp.Delete(ctx, node) + if err := fs.tp.Delete(ctx, node); err != nil { + return nil, err + } + return &storage.DeleteResult{ + SpaceOwner: node.SpaceOwnerOrManager(ctx), + ResourceId: &provider.ResourceId{ + SpaceId: node.SpaceID, + OpaqueId: node.ID, + }, + }, nil } // Download returns a reader to the specified resource @@ -1270,7 +947,7 @@ func (fs *Decomposedfs) Download(ctx context.Context, ref *provider.Reference, o return nil, nil, err } - if n.IsProcessing(ctx) { + if n.IsProcessing(ctx) && !fs.recoverInterruptedUpload(ctx, n) { return nil, nil, errtypes.TooEarly("file is still being processed") } @@ -1330,31 +1007,36 @@ func (fs *Decomposedfs) GetLock(ctx context.Context, ref *provider.Reference) (* } // SetLock puts a lock on the given reference -func (fs *Decomposedfs) SetLock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) error { +func (fs *Decomposedfs) SetLock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) (*storage.SetLockResult, error) { ctx, span := tracer.Start(ctx, "SetLock") defer span.End() node, err := fs.lu.NodeFromResource(ctx, ref) if err != nil { - return errors.Wrap(err, "Decomposedfs: error resolving ref") + return nil, errors.Wrap(err, "Decomposedfs: error resolving ref") } if !node.Exists { - return errtypes.NotFound(filepath.Join(node.ParentID, node.Name)) + return nil, errtypes.NotFound(filepath.Join(node.ParentID, node.Name)) } rp, err := fs.p.AssemblePermissions(ctx, node) switch { case err != nil: - return err + return nil, err case !rp.InitiateFileUpload: f, _ := storagespace.FormatReference(ref) if rp.Stat { - return errtypes.PermissionDenied(f) + return nil, errtypes.PermissionDenied(f) } - return errtypes.NotFound(f) + return nil, errtypes.NotFound(f) } - return node.SetLock(ctx, lock) + spaceOwner := node.SpaceOwnerOrManager(ctx) + + if err := node.SetLock(ctx, lock); err != nil { + return nil, err + } + return &storage.SetLockResult{SpaceOwner: spaceOwner, SpaceID: node.SpaceID}, nil } // RefreshLock refreshes an existing lock on the given reference @@ -1390,35 +1072,40 @@ func (fs *Decomposedfs) RefreshLock(ctx context.Context, ref *provider.Reference } // Unlock removes an existing lock from the given reference -func (fs *Decomposedfs) Unlock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) error { +func (fs *Decomposedfs) Unlock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) (*storage.UnlockResult, error) { ctx, span := tracer.Start(ctx, "Unlock") defer span.End() if lock.LockId == "" { - return errtypes.BadRequest("missing lockid") + return nil, errtypes.BadRequest("missing lockid") } node, err := fs.lu.NodeFromResource(ctx, ref) if err != nil { - return errors.Wrap(err, "Decomposedfs: error resolving ref") + return nil, errors.Wrap(err, "Decomposedfs: error resolving ref") } if !node.Exists { - return errtypes.NotFound(filepath.Join(node.ParentID, node.Name)) + return nil, errtypes.NotFound(filepath.Join(node.ParentID, node.Name)) } rp, err := fs.p.AssemblePermissions(ctx, node) switch { case err != nil: - return err + return nil, err case !rp.InitiateFileUpload: // TODO do we need a dedicated permission? f, _ := storagespace.FormatReference(ref) if rp.Stat { - return errtypes.PermissionDenied(f) + return nil, errtypes.PermissionDenied(f) } - return errtypes.NotFound(f) + return nil, errtypes.NotFound(f) } - return node.Unlock(ctx, lock) + spaceOwner := node.SpaceOwnerOrManager(ctx) + + if err := node.Unlock(ctx, lock); err != nil { + return nil, err + } + return &storage.UnlockResult{SpaceOwner: spaceOwner, SpaceID: node.SpaceID}, nil } func (fs *Decomposedfs) ListRecycle(ctx context.Context, space *provider.Reference, key, relativePath string) ([]*provider.RecycleItem, error) { @@ -1457,16 +1144,16 @@ func (fs *Decomposedfs) ListRecycle(ctx context.Context, space *provider.Referen // The key is used to determine the recycle item. It is the node id of the recycle item, returned by ListRecycle // The relativePath is the path is the path relative to the recycle item in case a child should be restored // The restoreRef is the reference where the item should be restored to -func (fs *Decomposedfs) RestoreRecycleItem(ctx context.Context, space *provider.Reference, key, relativePath string, restoreRef *provider.Reference) error { +func (fs *Decomposedfs) RestoreRecycleItem(ctx context.Context, space *provider.Reference, key, relativePath string, restoreRef *provider.Reference) (*storage.RestoreRecycleItemResult, error) { _, span := tracer.Start(ctx, "RestoreRecycleItem") defer span.End() spaceID := space.GetResourceId().GetSpaceId() if spaceID == "" { - return errtypes.BadRequest("missing space reference, needs a space id") + return nil, errtypes.BadRequest("missing space reference, needs a space id") } if key == "" && relativePath != "" { - return errtypes.BadRequest("key is required when navigating with a path") + return nil, errtypes.BadRequest("key is required when navigating with a path") } trashItem := &provider.ResourceId{ @@ -1476,31 +1163,31 @@ func (fs *Decomposedfs) RestoreRecycleItem(ctx context.Context, space *provider. restoreBaseNode, err := fs.lu.NodeFromID(ctx, trashItem) if err != nil { - return err + return nil, err } // check permissions of deleted node rp, err := fs.p.AssembleTrashPermissions(ctx, restoreBaseNode) switch { case err != nil: - return err + return nil, err case !rp.RestoreRecycleItem: if rp.Stat { - return errtypes.PermissionDenied(key) + return nil, errtypes.PermissionDenied(key) } - return errtypes.NotFound(key) + return nil, errtypes.NotFound(key) } restoredNode, err := fs.trashbin.RestoreRecycleItem(ctx, spaceID, key, relativePath, restoreRef) if err != nil { - return err + return nil, err } var sizeDiff int64 if restoredNode.IsDir(ctx) { treeSize, err := restoredNode.GetTreeSize(ctx) if err != nil { - return err + return nil, err } sizeDiff = int64(treeSize) @@ -1512,7 +1199,10 @@ func (fs *Decomposedfs) RestoreRecycleItem(ctx context.Context, space *provider. sizeDiff = restoredNode.Blobsize } - return fs.tp.Propagate(ctx, restoredNode, sizeDiff) + if err := fs.tp.Propagate(ctx, restoredNode, sizeDiff); err != nil { + return nil, err + } + return &storage.RestoreRecycleItemResult{SpaceOwner: restoredNode.SpaceOwnerOrManager(ctx), SpaceID: restoredNode.SpaceID}, nil } func (fs *Decomposedfs) PurgeRecycleItem(ctx context.Context, space *provider.Reference, key, relativePath string) error { diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/metadata.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/metadata.go index a38c2f0b7b..3e538b2de0 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/metadata.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/metadata.go @@ -57,7 +57,7 @@ func (fs *Decomposedfs) SetArbitraryMetadata(ctx context.Context, ref *provider. } // Set space owner in context - storagespace.ContextSendSpaceOwnerID(ctx, n.SpaceOwnerOrManager(ctx)) + storagespace.ContextSetSpaceOwner(ctx, n.SpaceOwnerOrManager(ctx)) // check lock if err := n.CheckLock(ctx); err != nil { @@ -153,7 +153,7 @@ func (fs *Decomposedfs) UnsetArbitraryMetadata(ctx context.Context, ref *provide } // Set space owner in context - storagespace.ContextSendSpaceOwnerID(ctx, n.SpaceOwnerOrManager(ctx)) + storagespace.ContextSetSpaceOwner(ctx, n.SpaceOwnerOrManager(ctx)) // check lock if err := n.CheckLock(ctx); err != nil { diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/node/node.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/node/node.go index 4c775d2201..a941a92dfe 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/node/node.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/node/node.go @@ -58,6 +58,10 @@ import ( var tracer trace.Tracer +// ErrMissingParentID is returned when a node exists on disk but has no parent id, +// which means its metadata is gone and the node can no longer be resolved. +var ErrMissingParentID = errtypes.InternalError("Missing parent ID on node") + func init() { tracer = otel.Tracer("github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/node") } @@ -525,7 +529,7 @@ func readNode(ctx context.Context, lu PathLookup, spaceID, nodeID, internalPath if _, ok := lu.MetadataBackend().(metadata.MessagePackBackend); ok { appctx.GetLogger(ctx).Error().Str("path", n.InternalPath()).Str("nodeid", n.ID).Interface("attrs", attrs).Bytes("messagepack", d).Msg("missing parent id") } - return nil, errtypes.InternalError("Missing parent ID on node") + return nil, ErrMissingParentID } if n.Type(ctx) == provider.ResourceType_RESOURCE_TYPE_FILE { @@ -1674,12 +1678,12 @@ func (n *Node) DeleteRevision(ctx context.Context, versionID string) (string, er return n.deleteRevision(ctx, n.ID+RevisionIDDelimiter+versionID) } - revisionPath, err := n.getLatestRevision(ctx) + reverted, err := n.RevertLatestRevision(ctx) if err != nil { return "", err } - if revisionPath == "" { + if !reverted { // there is no revision - delete the node unlock, err := n.lu.MetadataBackend().Lock(n) if err != nil { @@ -1695,11 +1699,6 @@ func (n *Node) DeleteRevision(ctx context.Context, versionID string) (string, er return "", nil } - latestID := strings.TrimPrefix(revisionPath, n.lu.VersionPath(n.SpaceID, n.ID, "")) - if err := n.RevertUpload(ctx, latestID); err != nil { - return "", err - } - // we just deleted the current revision - remove processing flag if set if uploadid, err := n.ProcessingID(ctx); err == nil { return "", n.UnmarkProcessing(ctx, uploadid) @@ -1750,6 +1749,32 @@ func (n *Node) deleteRevision(ctx context.Context, revisionID string) (string, e return blobID, nil } +// RevertLatestRevision reverts the upload that created the node's latest +// revision: the revision is restored onto the node and removed. Unlike +// DeleteRevision it neither purges the node when there is no revision nor +// touches the processing flag. It returns false if there is no revision to +// restore. +func (n *Node) RevertLatestRevision(ctx context.Context) (bool, error) { + revisionPath, err := n.getLatestRevision(ctx) + if err != nil { + return false, err + } + if revisionPath == "" { + return false, nil + } + return true, n.RevertUpload(ctx, strings.TrimPrefix(revisionPath, n.lu.VersionPath(n.SpaceID, n.ID, ""))) +} + +// LatestRevisionKey returns the version key of the node's latest revision, or "" if it has +// none. +func (n *Node) LatestRevisionKey(ctx context.Context) (string, error) { + revisionPath, err := n.getLatestRevision(ctx) + if err != nil || revisionPath == "" { + return "", err + } + return strings.TrimPrefix(revisionPath, n.lu.VersionPath(n.SpaceID, n.ID, "")), nil +} + func (n *Node) getLatestRevision(ctx context.Context) (string, error) { revPrefix := n.lu.VersionPath(n.SpaceID, n.ID, "") revisions, err := filepath.Glob(n.lu.VersionPath(n.SpaceID, n.ID, "*")) diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/node/permissions.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/node/permissions.go index 1f4ea0da49..27f2b14128 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/node/permissions.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/node/permissions.go @@ -101,7 +101,8 @@ func ServiceAccountPermissions() *provider.ResourcePermissions { Delete: true, // for cli restore command with replace option CreateContainer: true, // for space provisioning AddGrant: true, // for initial project space member assignment - ListGrants: true, // for initial project space member assignment + UpdateGrant: true, // for automatic space membership management + ListGrants: true, // for initial project space member assignment and automatic space membership management } } diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/permissions/spacepermissions.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/permissions/spacepermissions.go index 82a093710e..04d110bdec 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/permissions/spacepermissions.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/permissions/spacepermissions.go @@ -7,6 +7,7 @@ import ( cs3permissions "github.com/cs3org/go-cs3apis/cs3/permissions/v1beta1" v1beta11 "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1" provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" + "github.com/opencloud-eu/reva/v2/pkg/conversions" ctxpkg "github.com/opencloud-eu/reva/v2/pkg/ctx" "github.com/opencloud-eu/reva/v2/pkg/rgrpc/todo/pool" "github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/node" @@ -144,19 +145,27 @@ func (p Permissions) checkPermission(ctx context.Context, perm string, ref *prov return checkRes.Status.Code == v1beta11.Code_CODE_OK } -// IsManager returns true if the given resource permissions evaluate the user as "manager" -func IsManager(rp *provider.ResourcePermissions) bool { - return rp.RemoveGrant +// editorPerms is the smallest space editor bitmap. Every richer space editor variant and the +// manager role are supersets of it, viewers are not. +var editorPerms = conversions.NewSpaceEditorWithoutVersionsWithoutTrashbinRole().CS3ResourcePermissions() + +// IsSpaceManager returns true if the given resource permissions evaluate the user as "Space manager". +// A manager holds AddGrant, UpdateGrant and RemoveGrant, a single grant management bit is not enough. +// DenyGrant is not required, so manager and coowner grants that predate it still count. +func IsSpaceManager(rp *provider.ResourcePermissions) bool { + return rp.GetAddGrant() && rp.GetUpdateGrant() && rp.GetRemoveGrant() } -// IsEditor returns true if the given resource permissions evaluate the user as "editor" -func IsEditor(rp *provider.ResourcePermissions) bool { - return rp.InitiateFileUpload +// IsSpaceEditor returns true if the given resource permissions evaluate the user as "Space editor" +func IsSpaceEditor(rp *provider.ResourcePermissions) bool { + return conversions.SufficientCS3Permissions(rp, editorPerms) } -// IsViewer returns true if the given resource permissions evaluate the user as "viewer" -func IsViewer(rp *provider.ResourcePermissions) bool { - return rp.Stat +// IsSpaceViewer returns true if the given resource permissions evaluate the user as "Space viewer". +// NewSpaceViewerRole cannot be used because it carries ListRecycle, which the space editors +// without trashbin lack. +func IsSpaceViewer(rp *provider.ResourcePermissions) bool { + return rp.GetStat() && rp.GetGetPath() && rp.GetListGrants() } func spaceRef(spaceid string) *provider.Reference { diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/prepare_upload.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/prepare_upload.go new file mode 100644 index 0000000000..fbc3c6bdce --- /dev/null +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/prepare_upload.go @@ -0,0 +1,622 @@ +// Copyright 2026 OpenCloud GmbH +// SPDX-License-Identifier: Apache-2.0 + +package decomposedfs + +import ( + "context" + "fmt" + "os" + "path/filepath" + "strconv" + "strings" + "time" + + provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" + "github.com/pkg/errors" + + "github.com/opencloud-eu/reva/v2/pkg/appctx" + ctxpkg "github.com/opencloud-eu/reva/v2/pkg/ctx" + "github.com/opencloud-eu/reva/v2/pkg/errtypes" + "github.com/opencloud-eu/reva/v2/pkg/storage" + "github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/metadata" + "github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/metadata/prefixes" + "github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/node" + "github.com/opencloud-eu/reva/v2/pkg/storagespace" +) + +// PrepareCreatesNode reports that PrepareUpload creates a new file's node. +func (fs *Decomposedfs) PrepareCreatesNode() bool { + return true +} + +// PrepareUpload finalizes node metadata after bytes are received, before postprocessing, +// and marks the node as processing for sessionID. A new file's node is created here, under +// the id the ref carries. CommitUpload is called after postprocessing completes. +// +// The previous version is snapshotted through the tree's CreateRevision, like the legacy +// upload path does: posix copies the current content, decomposedfs only the metadata. When +// another upload is still processing the node, it is snapshotted even with versioning +// disabled, together with that upload's processing mark: if this upload is rolled back, the +// other one is restored and can still finish. +// +// With info.Source set and a blobstore that keeps blobs apart from the nodes, the upload is +// finished right here: the blob is stored before the node points to it, and the node is +// never marked. Readers get either the old or the new content, and an interrupted upload +// leaves no processing mark that nothing would ever remove. +func (fs *Decomposedfs) PrepareUpload(ctx context.Context, ref *provider.Reference, sessionID string, info storage.UploadInfo) (*storage.PrepareUploadResult, error) { + ctx, span := tracer.Start(ctx, "PrepareUpload") + defer span.End() + + n, err := fs.lu.NodeFromResource(ctx, ref) + if err != nil { + appctx.GetLogger(ctx).Error().Err(err).Msg("PrepareUpload: unexpected NodeFromResource failure") + return nil, errtypes.InternalError("PrepareUpload: node lookup failed unexpectedly") + } + // a new file nobody has created yet: PrepareUpload creates it + create := !n.Exists && !info.NodeExisted && info.ParentID != "" && info.Name != "" + if !n.Exists && !create { + return nil, errtypes.NotFound(ref.String()) + } + if create { + if err := fs.checkNewFileParent(ctx, n.SpaceID, info); err != nil { + return nil, err + } + n.ParentID = info.ParentID + n.Name = info.Name + } + + var ( + committed bool + // only a node this upload created is purged, one it is creating only once + // the name is its own: Purge removes the name + purge = !info.NodeExisted && !create + + // the upload is finished right here, see above + inline = info.Source != nil && (info.Source.Path != "" || info.Source.Body != nil) && fs.separateBlobs + stored bool + switched bool + ) + blob := node.New(n.SpaceID, n.ID, "", "", info.Size, sessionID, provider.ResourceType_RESOURCE_TYPE_FILE, nil, fs.lu) + storeBlob := func() error { + var err error + if info.Source.Path != "" { + err = fs.tp.WriteBlob(blob, info.Source.Path) + } else { + err = fs.tp.WriteBlobFromReader(blob, info.Source.Body, info.Source.Length) + } + if err != nil { + if derr := fs.tp.DeleteBlob(blob); derr != nil { + appctx.GetLogger(ctx).Error().Err(derr).Str("nodeid", n.ID).Str("blobid", sessionID).Msg("could not clean up the blob of a failed write") + } + // the staged bytes are still the only copy of the upload + return fmt.Errorf("%w: %w", storage.ErrSourceNotStored, err) + } + stored = true + return nil + } + // a failed write of the node might have happened anyway, then the node + // might point to the blob: rather leak it than lose the content + defer func() { + if !stored || committed || switched { + return + } + if err := fs.tp.DeleteBlob(blob); err != nil { + appctx.GetLogger(ctx).Error().Err(err).Str("nodeid", n.ID).Str("blobid", sessionID).Msg("could not delete the blob of a failed upload") + } + }() + // registered before the lock is taken, so it runs once the lock is released. + // Purge, not trash: the file never had content, and Purge needs no Delete permission + defer func() { + if committed || !purge { + return + } + if err := n.Purge(ctx); err != nil { + appctx.GetLogger(ctx).Error().Err(err).Str("nodeid", n.ID).Msg("could not purge new node after failed prepare") + } + }() + + n.SpaceRoot, err = node.ReadNode(ctx, fs.lu, n.SpaceID, n.SpaceID, "", false, nil, false) + if err != nil { + return nil, err + } + + if create { + // a node still to be created holds no lock, so any lock id is a mismatch + if lockID, _ := ctxpkg.ContextGetLockID(ctx); lockID != "" { + return nil, errtypes.Aborted("not locked") + } + } else if err := n.CheckLock(ctx); err != nil { + return nil, err + } + + // scope to space owner GID for posix deployments; no-op with NullMapper + if spaceGID, ok := ctx.Value(CtxKeySpaceGID).(uint32); ok { + unscope, err := fs.um.ScopeUserByIds(-1, int(spaceGID)) + if err != nil { + return nil, errors.Wrap(err, "failed to scope user") + } + if unscope != nil { + defer func() { _ = unscope() }() + } + } + + var unlock metadata.UnlockFunc + if create { + // Before the node exists: an upload interrupted while its blob is written + // must not leave a node without metadata behind, which blocks the name. + if inline { + if err := storeBlob(); err != nil { + return nil, err + } + } + // InitNewNode refuses a name already taken, checks the quota, and on failure + // removes what it made and releases its lock. It returns the node lock. + unlock, err = fs.tp.InitNewNode(ctx, n, uint64(info.Size)) + if err != nil { + return nil, err + } + purge = true + } else { + unlock, err = fs.lu.MetadataBackend().Lock(n) + if err != nil { + return nil, err + } + } + defer func() { + if err := unlock(); err != nil { + appctx.GetLogger(ctx).Error().Err(err).Str("nodeid", n.ID).Msg("could not close lock") + } + }() + + var ( + sizeDiff int64 + versionCreated bool + versionNode *node.BaseNode + oldAttrs node.Attributes + oldMtime time.Time + ) + + defer func() { + if committed { + return + } + if versionCreated { + removeRevision(ctx, fs.lu, versionNode) + } + if info.NodeExisted && oldAttrs != nil { + // mtime goes in the same batch: we still hold the metadata lock and + // SetMTime would try to retake it + if err := fs.lu.TimeManager().OverrideMtime(ctx, n, &oldAttrs, oldMtime); err != nil { + appctx.GetLogger(ctx).Error().Err(err).Str("nodeid", n.ID).Msg("could not restore node mtime during rollback") + } + if err := n.SetXattrsWithContext(ctx, oldAttrs); err != nil { + appctx.GetLogger(ctx).Error().Err(err).Str("nodeid", n.ID).Msg("could not restore node xattrs during rollback") + } + // restoring only rewrites the old keys, so the mark this upload added would stay + if _, ok := oldAttrs[prefixes.StatusPrefix]; !ok { + if err := n.RemoveXattr(ctx, prefixes.StatusPrefix); err != nil && !metadata.IsAttrUnset(err) { + appctx.GetLogger(ctx).Error().Err(err).Str("nodeid", n.ID).Msg("could not remove processing mark during rollback") + } + } + } + }() + + var ( + old *node.Node + overwrite bool + oldBlobsize int64 + ) + if info.NodeExisted { + old, err = node.ReadNode(ctx, fs.lu, n.SpaceID, n.ID, "", false, nil, false) + if err != nil { + return nil, errors.Wrap(err, "PrepareUpload: failed to read existing node") + } + overwrite = old.BlobID != "" + oldBlobsize = old.Blobsize + } + + // also for new files: the coordinator's check fails open without GetQuota + // permission, and CheckQuota guards disk space too. InitNewNode has checked a + // node it created. + if !create { + if _, err := node.CheckQuota(ctx, n.SpaceRoot, overwrite, uint64(oldBlobsize), uint64(info.Size)); err != nil { + return nil, err + } + } + + if info.NodeExisted { + oldMtime, err = old.GetMTime(ctx) + if err != nil { + return nil, err + } + oldEtag, err := node.CalculateEtag(old.ID, oldMtime) + if err != nil { + return nil, err + } + + if info.IfMatch != "" && info.IfMatch != oldEtag { + return nil, errtypes.Aborted("etag mismatch") + } + if info.IfNoneMatch != "" { + if info.IfNoneMatch == "*" { + return nil, errtypes.Aborted("etag mismatch, resource exists") + } + for _, tag := range strings.Split(info.IfNoneMatch, ",") { + if tag == oldEtag { + return nil, errtypes.Aborted("etag mismatch") + } + } + } + if !info.IfUnmodifiedSince.IsZero() && oldMtime.After(info.IfUnmodifiedSince) { + return nil, errtypes.Aborted("if-unmodified-since mismatch") + } + + // capture full node xattrs for rollback before any write + oldAttrs, err = fs.lu.MetadataBackend().All(ctx, n) + if err != nil { + return nil, err + } + + // another upload is still processing the node: keep its state, so a rollback + // of this upload can hand the node back to it + // an upload that finished right away clears a mark by emptying it + supersededMark := oldAttrs[prefixes.StatusPrefix] + superseding := strings.HasPrefix(string(supersededMark), node.ProcessingStatus) + if !fs.o.DisableVersioning || superseding { + timestamp := oldMtime.UTC().Format(time.RFC3339Nano) + versionPath, err := fs.tp.CreateRevision(ctx, n, timestamp) + if err != nil { + return nil, err + } + versionNode = node.NewBaseNode(n.SpaceID, n.ID+node.RevisionIDDelimiter+timestamp, fs.lu) + versionCreated = true + if err := os.Chtimes(versionPath, oldMtime, oldMtime); err != nil { + return nil, errtypes.InternalError(fmt.Sprintf("failed to set mtime on version node: %s", err)) + } + if superseding { + revisionAttrs := map[string][]byte{prefixes.StatusPrefix: supersededMark} + if fs.o.DisableVersioning { + // not a version, only kept for a rollback: a live commit removes it + revisionAttrs[uploadSnapshotAttr] = []byte("1") + } + if err := fs.lu.MetadataBackend().SetMultiple(ctx, versionNode, revisionAttrs); err != nil { + return nil, err + } + } + } + + sizeDiff = info.Size - old.Blobsize + } else { + // InitNewNode has cached a node it created + if c, ok := fs.lu.(node.IDCacher); ok && !create { + if err := c.CacheID(ctx, n.SpaceID, n.ID, filepath.Join(n.ParentPath(), n.Name)); err != nil { + appctx.GetLogger(ctx).Error().Err(err).Msg("failed to cache id") + } + } + sizeDiff = info.Size + } + + if inline && !create { + if err := storeBlob(); err != nil { + return nil, err + } + } + + attrs := node.Attributes{} + attrs.SetString(prefixes.IDAttr, n.ID) + attrs.SetInt64(prefixes.TypeAttr, int64(provider.ResourceType_RESOURCE_TYPE_FILE)) + attrs.SetString(prefixes.ParentidAttr, n.ParentID) + attrs.SetString(prefixes.NameAttr, n.Name) + attrs.SetString(prefixes.BlobIDAttr, sessionID) + attrs.SetInt64(prefixes.BlobsizeAttr, info.Size) + attrs[prefixes.ChecksumPrefix+"sha1"] = info.Checksums.SHA1 + attrs[prefixes.ChecksumPrefix+"md5"] = info.Checksums.MD5 + attrs[prefixes.ChecksumPrefix+"adler32"] = info.Checksums.Adler32 + if !inline { + // in the same batch, so marking the node costs no write of its own + attrs.SetString(prefixes.StatusPrefix, node.ProcessingStatus+sessionID) + } else if _, marked := oldAttrs[prefixes.StatusPrefix]; marked { + // The node is complete after this write, so the mark of another upload, + // like one that was interrupted, goes in the same write. Removing it + // beforehand could leave the node pointing to that upload's blob without + // the mark that recovering the upload relies on. + attrs.SetString(prefixes.StatusPrefix, "") + } + + mtime := time.Now() + if !info.MTime.IsZero() { + mtime = info.MTime + } + if err := fs.lu.TimeManager().OverrideMtime(ctx, n, &attrs, mtime); err != nil { + return nil, errors.Wrap(err, "failed to set mtime") + } + + switched = true + if err := n.SetXattrsWithContext(ctx, attrs); err != nil { + return nil, errors.Wrap(err, "could not write metadata") + } + + if err := fs.tp.Propagate(ctx, n, sizeDiff); err != nil { + return nil, errors.Wrap(err, "could not propagate size change") + } + committed = true + if inline { + // what CommitUpload does after a live commit: the revisions kept only + // for a rollback of this upload served their purpose. Not before the + // upload can no longer fail: a rollback restores the node from them, + // and their blobs are deleted with them. + n.BlobID = sessionID + fs.removeRevisions(ctx, n) + } + + result := &storage.PrepareUploadResult{VersionCreated: versionCreated, SizeDiff: sizeDiff, Committed: inline} + if !info.NodeExisted { + // read off the disk, not through ListGrants: an uploader who cannot see the + // space root still needs the manager of a project space reported + result.SpaceOwner = n.SpaceOwnerOrManager(ctx) + } + return result, nil +} + +// checkNewFileParent re-checks, for a file PrepareUpload is about to create, what +// TouchFile would have checked: the parent still exists, and the user may still upload +// into it. Either may have changed while the bytes were in flight. +func (fs *Decomposedfs) checkNewFileParent(ctx context.Context, spaceID string, info storage.UploadInfo) error { + parentID := &provider.ResourceId{SpaceId: spaceID, OpaqueId: info.ParentID} + parent, err := fs.lu.NodeFromID(ctx, parentID) + if err != nil { + return errtypes.InternalError(err.Error()) + } + f, _ := storagespace.FormatReference(&provider.Reference{ResourceId: parentID, Path: info.Name}) + if !parent.Exists { + return errtypes.NotFound(f) + } + + rp, err := fs.p.AssemblePermissions(ctx, parent) + switch { + case err != nil: + return err + case !rp.InitiateFileUpload: + if rp.Stat { + return errtypes.PermissionDenied(f) + } + return errtypes.NotFound(f) + } + return nil +} + +// removeRevision deletes a revision PrepareUpload created, with its metadata, while the +// caller holds the node lock (Node.DeleteRevision would try to take it again). Its blob +// is kept: the revision shares it with the node, whose old metadata is being restored. +func removeRevision(ctx context.Context, lu node.PathLookup, revisionNode *node.BaseNode) { + log := appctx.GetLogger(ctx).With().Str("revisionid", revisionNode.ID).Logger() + if err := os.Remove(revisionNode.InternalPath()); err != nil && !errors.Is(err, os.ErrNotExist) { + log.Error().Err(err).Msg("could not remove revision during rollback") + } + if err := lu.MetadataBackend().Purge(ctx, revisionNode); err != nil && !errors.Is(err, os.ErrNotExist) { + log.Error().Err(err).Msg("could not purge revision metadata during rollback") + } + if err := os.Remove(lu.MetadataBackend().LockfilePath(revisionNode)); err != nil && !errors.Is(err, os.ErrNotExist) { + log.Error().Err(err).Msg("could not remove revision lockfile during rollback") + } +} + +// RollbackUpload reverts the node state written by PrepareUpload after a failed or aborted +// postprocessing run. It restores the previous revision and reverts the optimistic size +// propagation. Unlike upstream it never purges an existing node: without a revision (versioning +// disabled) the previous metadata cannot be restored, so it returns an error instead. On posix +// this also keeps the file itself, which still holds the previous content until CommitUpload. +// When the node metadata has become unreadable the ids recorded in info are used to release +// its quota, and to remove the node if the upload created it. +func (fs *Decomposedfs) RollbackUpload(ctx context.Context, ref *provider.Reference, sessionID string, info storage.RollbackInfo) error { + n, err := fs.lu.NodeFromResource(ctx, ref) + if err != nil { + if !errors.Is(err, node.ErrMissingParentID) { + // the node might only be temporarily unreadable, e.g. because a cache + // is unavailable. Do not treat it as orphaned. + return err + } + // The node metadata is unreadable, so the upload can never finish and its + // quota would stay consumed forever. + return fs.rollbackOrphaned(ctx, ref, sessionID, info, err) + } + if !n.Exists { + return nil // nothing was written yet + } + n.SpaceRoot, err = node.ReadNode(ctx, fs.lu, n.SpaceID, n.SpaceID, "", false, nil, false) + if err != nil { + return err + } + + curProcessingID, err := n.ProcessingID(ctx) + if err != nil { + return fmt.Errorf("RollbackUpload: could not read processing ID: %w", err) + } + if curProcessingID != sessionID { + // a newer upload took over the node. The revision it kept of this upload would + // hand the node back to an upload that is gone. + fs.retireUploadRevision(ctx, n, sessionID, info.NodeExisted) + return nil + } + + sizeDiff := info.SizeDiff + if info.NodeExisted { + restored, purge, err := fs.restoreLatestRevision(ctx, n) + if err != nil { + return err + } + if !restored { + return errtypes.PreconditionFailed("RollbackUpload: no revision to restore for node " + n.ID) + } + if purge { + // the file was created by an upload that was rolled back while this one + // was processing, so nothing is left to keep + if err := n.Purge(ctx); err != nil { + return fmt.Errorf("RollbackUpload: could not purge node: %w", err) + } + sizeDiff += n.Blobsize + } + } else { + // the upload created this node, so undo it. Purge, not trash: the file never + // became visible, and Purge needs no Delete permission + if err := n.Purge(ctx); err != nil { + return fmt.Errorf("RollbackUpload: could not purge node: %w", err) + } + } + + if sizeDiff != 0 { + if err := fs.tp.Propagate(ctx, n, -sizeDiff); err != nil { + appctx.GetLogger(ctx).Error().Err(err).Msg("RollbackUpload: could not revert propagate") + } + } + return nil +} + +// restoreLatestRevision restores the node from the revision PrepareUpload created, its +// content included on posix, and removes the revision. If the revision kept the processing +// mark of an upload this one superseded, the mark is restored too, so that upload can still +// finish. It reports false if the node has no revision, and purge if the revision says the +// file should not exist anymore (see retireUploadRevision); n then describes the restored +// state, with the size the file accounts for. +func (fs *Decomposedfs) restoreLatestRevision(ctx context.Context, n *node.Node) (restored, purge bool, err error) { + unlock, err := fs.lu.MetadataBackend().Lock(n) + if err != nil { + return false, false, err + } + defer func() { + if err := unlock(); err != nil { + appctx.GetLogger(ctx).Error().Err(err).Str("nodeid", n.ID).Msg("could not close lock") + } + }() + + key, err := n.LatestRevisionKey(ctx) + if err != nil || key == "" { + return false, false, err + } + revisionNode := node.NewBaseNode(n.SpaceID, n.ID+node.RevisionIDDelimiter+key, fs.lu) + revisionAttrs, err := fs.lu.MetadataBackend().All(ctx, revisionNode) + if err != nil { + return false, false, err + } + + var mtime time.Time + if v, ok := revisionAttrs[prefixes.MTimeAttr]; ok { + if mtime, err = time.Parse(time.RFC3339Nano, string(v)); err != nil { + return false, false, err + } + } + if err := fs.tp.RestoreRevision(ctx, revisionNode, n, mtime); err != nil { + return false, false, err + } + if mark, ok := revisionAttrs[prefixes.StatusPrefix]; ok { + if err := n.SetXattrsWithContext(ctx, node.Attributes{prefixes.StatusPrefix: mark}); err != nil { + return false, false, err + } + } + if v, ok := revisionAttrs[prefixes.BlobsizeAttr]; ok { + n.Blobsize, _ = strconv.ParseInt(string(v), 10, 64) + } + _, purge = revisionAttrs[purgeOnRestoreAttr] + + removeRevision(ctx, fs.lu, revisionNode) + return true, purge, nil +} + +// purgeOnRestoreAttr marks a revision kept for an upload that created the file and was +// rolled back while a newer upload was processing: restoring it removes the file. +var purgeOnRestoreAttr = prefixes.OcPrefix + "purgeonrestore" + +// uploadSnapshotAttr marks a revision PrepareUpload kept with versioning disabled, only so +// that a rollback can hand the node back to the upload it superseded. It is not a version. +var uploadSnapshotAttr = prefixes.OcPrefix + "uploadsnapshot" + +// retireUploadRevision handles the revision a newer upload kept of the upload sessionID, +// which is being rolled back. If that upload overwrote the file, the revision is dropped: +// the one it kept itself describes the file before it. If it created the file, there is +// nothing before it, so the revision is marked to remove the file should the newer upload +// be rolled back too. +func (fs *Decomposedfs) retireUploadRevision(ctx context.Context, n *node.Node, sessionID string, nodeExisted bool) { + log := appctx.GetLogger(ctx).With().Str("nodeid", n.ID).Str("sessionid", sessionID).Logger() + unlock, err := fs.lu.MetadataBackend().Lock(n) + if err != nil { + log.Error().Err(err).Msg("could not lock node") + return + } + defer func() { + if err := unlock(); err != nil { + log.Error().Err(err).Msg("could not close lock") + } + }() + + revision, revisionUnlock, err := fs.uploadRevision(ctx, n, sessionID) + if err != nil { + log.Error().Err(err).Msg("could not look up the upload's revision") + return + } + if revision == nil { + return + } + defer func() { _ = revisionUnlock() }() + + if nodeExisted { + removeRevision(ctx, fs.lu, &revision.BaseNode) + return + } + if err := revision.SetXattrsWithContext(ctx, node.Attributes{purgeOnRestoreAttr: []byte("1")}); err != nil { + log.Error().Err(err).Msg("could not mark the upload's revision") + } + if err := revision.RemoveXattr(ctx, prefixes.StatusPrefix); err != nil && !metadata.IsAttrUnset(err) { + log.Error().Err(err).Msg("could not remove the processing mark from the upload's revision") + } +} + +// rollbackOrphaned releases the quota of an upload whose node metadata is unreadable, using +// the node and parent ids the upload session recorded. It removes the node only if the upload +// created it and it is still empty. +func (fs *Decomposedfs) rollbackOrphaned(ctx context.Context, ref *provider.Reference, sessionID string, info storage.RollbackInfo, lookupErr error) error { + spaceID := ref.GetResourceId().GetSpaceId() + if info.NodeID == "" || info.ParentID == "" || spaceID == "" { + return fmt.Errorf("RollbackUpload: node lookup failed: %w", lookupErr) + } + log := appctx.GetLogger(ctx).With().Str("sessionid", sessionID).Str("nodeid", info.NodeID).Logger() + log.Info().Err(lookupErr).Msg("node unreadable, rolling back orphaned upload") + + n := node.New(spaceID, info.NodeID, info.ParentID, info.Filename, info.Size, sessionID, + provider.ResourceType_RESOURCE_TYPE_FILE, nil, fs.lu) + spaceRoot, err := node.ReadNode(ctx, fs.lu, spaceID, spaceID, "", false, nil, false) + if err != nil { + return fmt.Errorf("RollbackUpload: space root lookup failed: %w", err) + } + n.SpaceRoot = spaceRoot + + if info.SizeDiff != 0 { + // an error keeps the session, so the rollback can be retried + if err := fs.tp.Propagate(ctx, n, -info.SizeDiff); err != nil { + return fmt.Errorf("RollbackUpload: could not revert propagate: %w", err) + } + } + + // Only a node this upload created may be removed. An existing node holds the + // previous version, on posix the user's file itself, so it is left alone. + if info.NodeExisted { + return nil + } + // The node file stays empty until the upload is committed. If it has content, + // something outside of us wrote it, e.g. an editor saving atomically on posix, + // so keep it. + if fi, err := os.Stat(n.InternalPath()); err == nil && fi.Size() > 0 { + log.Info().Str("nodepath", n.InternalPath()).Msg("orphaned node has content, keeping it") + return nil + } + + // the orphaned node cannot be resolved by any other means, remove it together + // with its metadata. A missing node is fine: it may never have been created. + if err := fs.lu.PurgeNode(n); err != nil && !errors.Is(err, os.ErrNotExist) { + log.Error().Err(err).Str("nodepath", n.InternalPath()).Msg("RollbackUpload: removing orphaned node failed") + } + if err := fs.lu.MetadataBackend().Purge(ctx, n); err != nil && !errors.Is(err, os.ErrNotExist) { + log.Error().Err(err).Str("nodepath", n.InternalPath()).Msg("RollbackUpload: purging orphaned node metadata failed") + } + return nil +} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/recover.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/recover.go new file mode 100644 index 0000000000..b8583d4675 --- /dev/null +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/recover.go @@ -0,0 +1,117 @@ +// Copyright 2026 OpenCloud GmbH +// SPDX-License-Identifier: Apache-2.0 + +package decomposedfs + +import ( + "context" + "errors" + iofs "io/fs" + "os" + "path/filepath" + "strings" + "time" + + "github.com/opencloud-eu/reva/v2/pkg/appctx" + "github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/metadata/prefixes" + "github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/node" + "github.com/rs/zerolog" +) + +// interruptedUploadAge is how old the session of a processing node has to be +// before the upload is taken for interrupted. Until then it might still be +// running on an instance that does not write blobs first yet. +const interruptedUploadAge = 10 * time.Minute + +// recoverInterruptedUpload finishes a synchronous upload that was interrupted +// after its node had been switched to the new blob, e.g. by a crash. Older +// versions marked the node as processing for that time, and as nothing +// postprocesses synchronous uploads, the marker stayed forever. It reports +// whether the node is no longer processing. +// +// The upload sessions are the coordinator's, which keeps the same layout as +// the session store of older versions: / and .info. +func (fs *Decomposedfs) recoverInterruptedUpload(ctx context.Context, n *node.Node) bool { + if !fs.separateBlobs || fs.o.AsyncFileUploads { + // processing markers are expected here, postprocessing removes them + return false + } + log := appctx.GetLogger(ctx).With().Str("spaceid", n.SpaceID).Str("nodeid", n.ID).Logger() + + unlock, err := fs.lu.MetadataBackend().Lock(n) + if err != nil { + log.Error().Err(err).Msg("could not lock node to recover an interrupted upload") + return false + } + done, recovered := fs.finishInterruptedUpload(ctx, n, log) + _ = unlock() + + // Let clients see the change, once the node is unlocked like finished + // uploads do. The size difference might have been counted already, e.g. + // if the upload started while the store was async, so the tree size is + // left as it is. + if recovered { + if err := fs.tp.Propagate(ctx, n, 0); err != nil { + log.Error().Err(err).Msg("could not propagate a recovered upload") + } + } + return done +} + +// finishInterruptedUpload does the work of recoverInterruptedUpload with the +// node locked. Besides whether the node is no longer processing, it reports +// whether it recovered the upload itself. +func (fs *Decomposedfs) finishInterruptedUpload(ctx context.Context, n *node.Node, log zerolog.Logger) (done, recovered bool) { + // the node might have changed while waiting for the lock + n.ResetXattrsCache() + attrs, err := n.Xattrs(ctx) + if err != nil { + log.Error().Err(err).Msg("could not read node to recover an interrupted upload") + return false, false + } + n.BlobID = attrs.String(prefixes.BlobIDAttr) + n.Blobsize, _ = attrs.Int64(prefixes.BlobsizeAttr) + status := attrs.String(prefixes.StatusPrefix) + if !strings.HasPrefix(status, node.ProcessingStatus) { + return true, false + } + // uploads point the node to a blob named after their session, other + // markers are none of our business + uploadID := strings.TrimPrefix(status, node.ProcessingStatus) + if uploadID == "" || n.BlobID != uploadID { + return false, false + } + log = log.With().Str("uploadid", uploadID).Logger() + + binPath := filepath.Join(fs.o.UploadDirectory, uploadID) + infoPath := binPath + ".info" + if info, err := os.Stat(infoPath); err == nil && time.Since(info.ModTime()) < interruptedUploadAge { + return false, false + } + + if _, err := os.Stat(binPath); err == nil { + // the upload stopped before its blob was stored + if err := fs.tp.WriteBlob(n, binPath); err != nil { + log.Error().Err(err).Msg("could not store the blob of an interrupted upload") + return false, false + } + } + blob, err := fs.tp.ReadBlob(n) + if err != nil { + log.Error().Err(err).Msg("the blob of an interrupted upload is missing, the node stays marked as processing") + return false, false + } + _ = blob.Close() + + if err := n.RemoveXattr(ctx, prefixes.StatusPrefix); err != nil { + log.Error().Err(err).Msg("could not remove the processing status of an interrupted upload") + return false, false + } + for _, p := range []string{binPath, infoPath} { + if err := os.Remove(p); err != nil && !errors.Is(err, iofs.ErrNotExist) { + log.Error().Err(err).Str("path", p).Msg("could not remove a file of an interrupted upload") + } + } + log.Warn().Msg("recovered interrupted upload") + return true, true +} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/recycle.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/recycle.go index 8a7018d184..dbaf58471a 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/recycle.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/recycle.go @@ -38,7 +38,6 @@ import ( "github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/metadata/prefixes" "github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/node" "github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/tree" - "github.com/opencloud-eu/reva/v2/pkg/storagespace" ) type DecomposedfsTrashbin struct { @@ -379,9 +378,6 @@ func (tb *DecomposedfsTrashbin) RestoreRecycleItem(ctx context.Context, spaceID return nil, errtypes.NotFound(key) } - // Set space owner in context - storagespace.ContextSendSpaceOwnerID(ctx, rn.SpaceOwnerOrManager(ctx)) - // check we can write to the parent of the restore reference pp, err := tb.fs.p.AssemblePermissions(ctx, parent) switch { diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/revisions.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/revisions.go index b27e2fe4d2..5d022327ba 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/revisions.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/revisions.go @@ -30,6 +30,7 @@ import ( "github.com/opencloud-eu/reva/v2/pkg/appctx" "github.com/opencloud-eu/reva/v2/pkg/errtypes" + "github.com/opencloud-eu/reva/v2/pkg/storage" "github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/metadata/prefixes" "github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/node" "github.com/opencloud-eu/reva/v2/pkg/storagespace" @@ -54,7 +55,7 @@ func (fs *Decomposedfs) DownloadRevision(ctx context.Context, ref *provider.Refe } // RestoreRevision restores the specified revision of the resource -func (fs *Decomposedfs) RestoreRevision(ctx context.Context, ref *provider.Reference, revisionKey string) (returnErr error) { +func (fs *Decomposedfs) RestoreRevision(ctx context.Context, ref *provider.Reference, revisionKey string) (_ *storage.RestoreRevisionResult, returnErr error) { _, span := tracer.Start(ctx, "RestoreRevision") defer span.End() log := appctx.GetLogger(ctx) @@ -63,47 +64,46 @@ func (fs *Decomposedfs) RestoreRevision(ctx context.Context, ref *provider.Refer kp := strings.SplitN(revisionKey, node.RevisionIDDelimiter, 2) if len(kp) != 2 { log.Error().Str("revisionKey", revisionKey).Msg("malformed revisionKey") - return errtypes.NotFound(revisionKey) + return nil, errtypes.NotFound(revisionKey) } spaceID := ref.ResourceId.SpaceId // check if the node is available and has not been deleted n, err := node.ReadNode(ctx, fs.lu, spaceID, kp[0], "", false, nil, false) if err != nil { - return err + return nil, err } if !n.Exists { err = errtypes.NotFound(filepath.Join(n.ParentID, n.Name)) - return err + return nil, err } rp, err := fs.p.AssemblePermissions(ctx, n) switch { case err != nil: - return err + return nil, err case !rp.RestoreFileVersion: f, _ := storagespace.FormatReference(ref) if rp.Stat { - return errtypes.PermissionDenied(f) + return nil, errtypes.PermissionDenied(f) } - return errtypes.NotFound(f) + return nil, errtypes.NotFound(f) } - // Set space owner in context - storagespace.ContextSendSpaceOwnerID(ctx, n.SpaceOwnerOrManager(ctx)) + spaceOwner := n.SpaceOwnerOrManager(ctx) // check lock if err := n.CheckLock(ctx); err != nil { - return err + return nil, err } if n.IsProcessing(ctx) { - return errtypes.ResourceProcessing(ref.String()) + return nil, errtypes.ResourceProcessing(ref.String()) } // write lock node before copying metadata unlock, err := fs.lu.MetadataBackend().Lock(n) if err != nil { - return err + return nil, err } defer func() { _ = unlock() @@ -114,12 +114,12 @@ func (fs *Decomposedfs) RestoreRevision(ctx context.Context, ref *provider.Refer mtime, err := n.GetMTime(ctx) if err != nil { log.Error().Err(err).Interface("ref", ref).Str("originalnode", kp[0]).Str("revisionKey", revisionKey).Msg("cannot read mtime") - return err + return nil, err } // create a revision of the current node if _, err := fs.tp.CreateRevision(ctx, n, mtime.UTC().Format(time.RFC3339Nano)); err != nil { - return err + return nil, err } // revision 5, current 10 (restore a smaller blob) -> 5-10 = -5 @@ -127,14 +127,14 @@ func (fs *Decomposedfs) RestoreRevision(ctx context.Context, ref *provider.Refer revisionNode := node.NewBaseNode(spaceID, revisionKey, fs.lu) revisionSize, err := fs.lu.MetadataBackend().GetInt64(ctx, revisionNode, prefixes.BlobsizeAttr) if err != nil { - return errtypes.InternalError("failed to read blob size xattr from old revision") + return nil, errtypes.InternalError("failed to read blob size xattr from old revision") } sizeDiff := revisionSize - n.Blobsize // restore revision restoredRevisionPath := fs.lu.InternalPath(spaceID, revisionKey) if err := fs.tp.RestoreRevision(ctx, revisionNode, n, time.Now()); err != nil { - return err + return nil, err } // drop old revision @@ -151,7 +151,10 @@ func (fs *Decomposedfs) RestoreRevision(ctx context.Context, ref *provider.Refer log.Warn().Err(err).Interface("ref", ref).Str("originalnode", kp[0]).Str("revisionKey", revisionKey).Msg("could not purge old revision from cache, continuing") } - return fs.tp.Propagate(ctx, n, sizeDiff) + if err := fs.tp.Propagate(ctx, n, sizeDiff); err != nil { + return nil, err + } + return &storage.RestoreRevisionResult{SpaceOwner: spaceOwner, SpaceID: n.SpaceID}, nil } // DeleteRevision deletes the specified revision of the resource @@ -222,7 +225,7 @@ func (fs *Decomposedfs) getRevisionNode(ctx context.Context, ref *provider.Refer } // Set space owner in context - storagespace.ContextSendSpaceOwnerID(ctx, n.SpaceOwnerOrManager(ctx)) + storagespace.ContextSetSpaceOwner(ctx, n.SpaceOwnerOrManager(ctx)) return n, nil } diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/spaces.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/spaces.go index 99441e6794..1397cc31bb 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/spaces.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/spaces.go @@ -46,6 +46,7 @@ import ( "github.com/opencloud-eu/reva/v2/pkg/rgrpc/status" "github.com/opencloud-eu/reva/v2/pkg/rgrpc/todo/pool" sdk "github.com/opencloud-eu/reva/v2/pkg/sdk/common" + "github.com/opencloud-eu/reva/v2/pkg/storage" "github.com/opencloud-eu/reva/v2/pkg/storage/fs/posix/lookup" dfslookup "github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/lookup" "github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/metadata/prefixes" @@ -677,7 +678,7 @@ func (fs *Decomposedfs) UpdateStorageSpace(ctx context.Context, req *provider.Up } - if !restore && len(metadata) == 0 && !permissions.IsViewer(sp) { + if !restore && len(metadata) == 0 && !permissions.IsSpaceViewer(sp) { // you may land here when making an update request without changes // check if user has access to the drive before continuing return &provider.UpdateStorageSpaceResponse{ @@ -685,10 +686,10 @@ func (fs *Decomposedfs) UpdateStorageSpace(ctx context.Context, req *provider.Up }, nil } - if !permissions.IsManager(sp) { + if !permissions.IsSpaceManager(sp) { // We are not a space manager. We need to check for additional permissions. k := []string{prefixes.NameAttr, prefixes.SpaceDescriptionAttr, prefixes.SpaceContentTypeAttr} - if !permissions.IsEditor(sp) { + if !permissions.IsSpaceEditor(sp) { k = append(k, prefixes.SpaceReadmeAttr, prefixes.SpaceAliasAttr, prefixes.SpaceImageAttr) } @@ -722,6 +723,13 @@ func (fs *Decomposedfs) UpdateStorageSpace(ctx context.Context, req *provider.Up }, nil } } + + // capture old image id to delete it after successful update + var oldImageID string + if v, e := spaceNode.XattrString(ctx, prefixes.SpaceImageAttr); e == nil { + oldImageID = v + } + metadata[prefixes.TreeMTimeAttr] = []byte(time.Now().UTC().Format(time.RFC3339Nano)) err = spaceNode.SetXattrsWithContext(ctx, metadata) @@ -729,6 +737,21 @@ func (fs *Decomposedfs) UpdateStorageSpace(ctx context.Context, req *provider.Up return nil, err } + // housekeeping: if the space image is being updated, remove the old one + if newImageID, ok := metadata[prefixes.SpaceImageAttr]; ok { + if oldImageID != "" && oldImageID != string(newImageID) { + delRef := &provider.Reference{ + ResourceId: &provider.ResourceId{ + SpaceId: spaceID, + OpaqueId: oldImageID, + }, + } + // delete old image after new image was successfully set + _, _ = fs.Delete(ctx, delRef) + // silently ignore failed deletion + } + } + if restore { if err := spaceNode.SetDTime(ctx, nil); err != nil { return nil, err @@ -748,7 +771,7 @@ func (fs *Decomposedfs) UpdateStorageSpace(ctx context.Context, req *provider.Up } // DeleteStorageSpace deletes a storage space -func (fs *Decomposedfs) DeleteStorageSpace(ctx context.Context, req *provider.DeleteStorageSpaceRequest) error { +func (fs *Decomposedfs) DeleteStorageSpace(ctx context.Context, req *provider.DeleteStorageSpaceRequest) (*storage.DeleteStorageSpaceResult, error) { opaque := req.Opaque var purge bool if opaque != nil { @@ -757,25 +780,39 @@ func (fs *Decomposedfs) DeleteStorageSpace(ctx context.Context, req *provider.De _, spaceID, _, err := storagespace.SplitID(req.GetId().GetOpaqueId()) if err != nil { - return err + return nil, err } n, err := node.ReadNode(ctx, fs.lu, spaceID, spaceID, "", true, nil, false) // permission to read disabled space is checked later if err != nil { - return err + return nil, err + } + if !n.Exists { + return nil, errtypes.NotFound(spaceID) } st, err := n.SpaceRoot.XattrString(ctx, prefixes.SpaceTypeAttr) if err != nil { - return errtypes.InternalError(fmt.Sprintf("space %s does not have a spacetype, possible corrupt decompsedfs", n.GetID())) + return nil, errtypes.InternalError(fmt.Sprintf("space %s does not have a spacetype, possible corrupt decompsedfs", n.GetID())) } if err := canDeleteSpace(ctx, spaceID, st, purge, n, fs.p); err != nil { - return err + return nil, err } if purge { if !n.IsDisabled(ctx) { - return errtypes.NewErrtypeFromStatus(status.NewInvalid(ctx, "can't purge enabled space")) + return nil, errtypes.NewErrtypeFromStatus(status.NewInvalid(ctx, "can't purge enabled space")) + } + + // capture what the SpaceDeleted event needs before any destructive work + spaceName, _ := n.SpaceRoot.XattrString(ctx, prefixes.SpaceNameAttr) + grants, err := n.ListGrants(ctx) + if err != nil { + return nil, err + } + finalMembers, err := activeMembers(grants) + if err != nil { + return nil, err } // delete the blobs of all nodes first, so that a failed purge can be retried @@ -794,16 +831,16 @@ func (fs *Decomposedfs) DeleteStorageSpace(ctx context.Context, req *provider.De return err }) if err != nil { - return err + return nil, err } } spaceType, err := n.XattrString(ctx, prefixes.SpaceTypeAttr) if err != nil { - return err + return nil, err } if err := fs.spaceTypeIndex.Remove(spaceType, spaceID); err != nil { - return err + return nil, err } // the by-type index is handled above; also remove the space from the user @@ -820,10 +857,6 @@ func (fs *Decomposedfs) DeleteStorageSpace(ctx context.Context, req *provider.De sublog.Error().Err(err).Msg("could not remove owner from user index") } } - grants, err := n.ListGrants(ctx) - if err != nil { - sublog.Error().Err(err).Msg("could not list grants") - } for _, g := range grants { switch g.Grantee.Type { case provider.GranteeType_GRANTEE_TYPE_USER: @@ -849,7 +882,7 @@ func (fs *Decomposedfs) DeleteStorageSpace(ctx context.Context, req *provider.De // invalidate cache if err := fs.lu.MetadataBackend().Purge(ctx, n); err != nil { - return err + return nil, err } root := n.InternalPath() @@ -857,14 +890,14 @@ func (fs *Decomposedfs) DeleteStorageSpace(ctx context.Context, req *provider.De // remove space metadata if spaceRoot != "" { if err := removeSpaceRoot(spaceRoot); err != nil { - return err + return nil, err } } // invalidate id in cache if l, ok := fs.lu.(*lookup.Lookup); ok { if err := l.IDCache.DeleteByPath(ctx, root); err != nil { - return err + return nil, err } } @@ -872,12 +905,52 @@ func (fs *Decomposedfs) DeleteStorageSpace(ctx context.Context, req *provider.De // Note that this will fail when there are other spaceids starting with the same two digits. _ = os.Remove(filepath.Dir(root)) - return nil + return &storage.DeleteStorageSpaceResult{ + SpaceName: spaceName, + FinalMembers: finalMembers, + }, nil } // mark as disabled by writing a dtime attribute dtime := time.Now() - return n.SetDTime(ctx, &dtime) + if err := n.SetDTime(ctx, &dtime); err != nil { + return nil, err + } + return &storage.DeleteStorageSpaceResult{}, nil +} + +// activeMembers returns the permissions of all user and group grants that +// have not expired, keyed by grantee opaque id. Expired grants are skipped, +// they are removed together with the space. +func activeMembers(grants []*provider.Grant) (map[string]provider.ResourcePermissions, error) { + tmp := make(map[string]*provider.ResourcePermissions, len(grants)) + for _, g := range grants { + var id string + switch g.Grantee.Type { + case provider.GranteeType_GRANTEE_TYPE_USER: + id = g.Grantee.GetUserId().GetOpaqueId() + case provider.GranteeType_GRANTEE_TYPE_GROUP: + id = g.Grantee.GetGroupId().GetOpaqueId() + default: + continue + } + if g.Expiration != nil && isGrantExpired(g) { + continue + } + tmp[id] = g.Permissions + } + + // round trip through json to get value types without copying the + // protobuf internals (and their mutex) + b, err := json.Marshal(tmp) + if err != nil { + return nil, err + } + out := make(map[string]provider.ResourcePermissions, len(tmp)) + if err := json.Unmarshal(b, &out); err != nil { + return nil, err + } + return out, nil } // the value of `target` depends on the implementation: @@ -939,7 +1012,7 @@ func (fs *Decomposedfs) StorageSpaceFromNode(ctx context.Context, n *node.Node, if n.SpaceRoot.IsDisabled(ctx) { rp, err := fs.p.AssemblePermissions(ctx, n) - if err != nil || !permissions.IsManager(rp) { + if err != nil || !permissions.IsSpaceManager(rp) { return nil, errtypes.PermissionDenied(fmt.Sprintf("user %s is not allowed to list deleted spaces %s", user.Username, n.GetID())) } } @@ -1257,7 +1330,7 @@ func canDeleteSpace(ctx context.Context, spaceID string, typ string, purge bool, // space managers are allowed to disable their project spaces rp, err := p.AssemblePermissions(ctx, n) - if err == nil && !purge && permissions.IsManager(rp) { + if err == nil && !purge && permissions.IsSpaceManager(rp) { return nil } diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/tree/tree.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/tree/tree.go index 9bb49bfc25..4219859527 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/tree/tree.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/tree/tree.go @@ -34,6 +34,7 @@ import ( "github.com/google/uuid" "github.com/opencloud-eu/reva/v2/pkg/appctx" "github.com/opencloud-eu/reva/v2/pkg/errtypes" + "github.com/opencloud-eu/reva/v2/pkg/storage" "github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/lookup" "github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/metadata" "github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/metadata/prefixes" @@ -177,6 +178,9 @@ func (t *Tree) TouchFile(ctx context.Context, n *node.Node, markprocessing bool, } } + if storage.SkipTouchPropagation(ctx) { + return nil + } return t.Propagate(ctx, n, 0) } @@ -485,14 +489,13 @@ func (t *Tree) Delete(ctx context.Context, n *node.Node) (err error) { trashPath := trashNode.InternalPath() err = os.Rename(nodePath, trashPath) if err != nil { - // To roll back changes - // TODO remove symlink - // Roll back changes + _ = os.Remove(trashLink) _ = n.RemoveXattr(ctx, prefixes.TrashOriginAttr) return } err = t.lookup.MetadataBackend().Rename(n, trashNode) if err != nil { + _ = os.Remove(trashLink) _ = n.RemoveXattr(ctx, prefixes.TrashOriginAttr) _ = os.Rename(trashPath, nodePath) return @@ -506,10 +509,9 @@ func (t *Tree) Delete(ctx context.Context, n *node.Node) (err error) { // finally remove the entry from the parent dir if err = os.Remove(path); err != nil { - // To roll back changes - // TODO revert the rename - // TODO remove symlink - // Roll back changes + _ = t.lookup.MetadataBackend().Rename(trashNode, n) + _ = os.Rename(trashPath, nodePath) + _ = os.Remove(trashLink) _ = n.RemoveXattr(ctx, prefixes.TrashOriginAttr) return } @@ -670,15 +672,31 @@ func (t *Tree) InitNewNode(ctx context.Context, n *node.Node, fsize uint64) (met h, err := os.OpenFile(n.InternalPath(), os.O_CREATE|os.O_EXCL, 0600) subspan.End() if err != nil { - return unlock, err + // the node file is not ours, so there is nothing of ours to remove + releaseNewNodeLock(ctx, n, unlock) + if errors.Is(err, fs.ErrExist) { + return nil, errtypes.AlreadyExists(n.Name) + } + return nil, err } h.Close() + // from here the node file is ours, but the name may not be: a failure removes the + // node file and leaves the name to whichever upload linked it. Removed before + // unlocking, so nothing can open the node in between. + fail := func(err error) (metadata.UnlockFunc, error) { + if rErr := os.Remove(n.InternalPath()); rErr != nil { + appctx.GetLogger(ctx).Error().Err(rErr).Str("nodeid", n.ID).Msg("could not remove new node file") + } + releaseNewNodeLock(ctx, n, unlock) + return nil, err + } + _, subspan = tracer.Start(ctx, "node.CheckQuota") _, err = node.CheckQuota(ctx, n.SpaceRoot, false, 0, fsize) subspan.End() if err != nil { - return unlock, err + return fail(err) } // link child name to parent if it is new @@ -694,15 +712,22 @@ func (t *Tree) InitNewNode(ctx context.Context, n *node.Node, fsize uint64) (met log.Info().Err(err).Msg("initNewNode: symlink failed") if errors.Is(err, fs.ErrExist) { log.Info().Err(err).Msg("initNewNode: symlink already exists") - return unlock, errtypes.AlreadyExists(n.Name) + return fail(errtypes.AlreadyExists(n.Name)) } - return unlock, errors.Wrap(err, "Decomposedfs: could not symlink child entry") + return fail(errors.Wrap(err, "Decomposedfs: could not symlink child entry")) } log.Info().Msg("initNewNode: symlink created") return unlock, nil } +// releaseNewNodeLock releases the lock of a node InitNewNode failed to create. +func releaseNewNodeLock(ctx context.Context, n *node.Node, unlock metadata.UnlockFunc) { + if err := unlock(); err != nil { + appctx.GetLogger(ctx).Error().Err(err).Str("nodeid", n.ID).Msg("could not release new node lock") + } +} + func (t *Tree) removeNode(ctx context.Context, n *node.Node) error { path := n.InternalPath() logger := appctx.GetLogger(ctx).With().Str("spaceid", n.SpaceID).Str("nodeid", n.ID).Logger() diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/upload.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/upload.go index 06b24db830..ec25cf28f1 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/upload.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/upload.go @@ -20,441 +20,12 @@ package decomposedfs import ( "context" - "fmt" - "os" - "path/filepath" - "strings" - "time" provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" - "github.com/google/uuid" - "github.com/pkg/errors" - tusd "github.com/tus/tusd/v2/pkg/handler" - - "github.com/opencloud-eu/reva/v2/pkg/appctx" - ctxpkg "github.com/opencloud-eu/reva/v2/pkg/ctx" - "github.com/opencloud-eu/reva/v2/pkg/errtypes" - "github.com/opencloud-eu/reva/v2/pkg/rhttp/datatx/metrics" - "github.com/opencloud-eu/reva/v2/pkg/storage" - "github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/node" - "github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/upload" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/chunking" - "github.com/opencloud-eu/reva/v2/pkg/storagespace" - "github.com/opencloud-eu/reva/v2/pkg/utils" ) -// Upload uploads data to the given resource -// TODO Upload (and InitiateUpload) needs a way to receive the expected checksum. -// Maybe in metadata as 'checksum' => 'sha1 aeosvp45w5xaeoe' = lowercase, space separated? -func (fs *Decomposedfs) Upload(ctx context.Context, req storage.UploadRequest, uff storage.UploadFinishedFunc) (*provider.ResourceInfo, error) { - _, span := tracer.Start(ctx, "Upload") - defer span.End() - up, err := fs.GetUpload(ctx, req.Ref.GetPath()) - if err != nil { - return &provider.ResourceInfo{}, errors.Wrap(err, "Decomposedfs: error retrieving upload") - } - - session := up.(*upload.DecomposedFsSession) - - ctx = session.Context(ctx) - - if session.Chunk() != "" { // check chunking v1 - p, assembledFile, err := fs.chunkHandler.WriteChunk(session.Chunk(), req.Body) - if err != nil { - return &provider.ResourceInfo{}, err - } - if p == "" { - if err = session.Terminate(ctx); err != nil { - return &provider.ResourceInfo{}, errors.Wrap(err, "Decomposedfs: error removing auxiliary files") - } - return &provider.ResourceInfo{}, errtypes.PartialContent(req.Ref.String()) - } - fd, err := os.Open(assembledFile) - if err != nil { - return &provider.ResourceInfo{}, errors.Wrap(err, "Decomposedfs: error opening assembled file") - } - defer func() { - _ = fd.Close() - }() - defer func() { - _ = os.RemoveAll(assembledFile) - }() - req.Body = fd - - size, err := session.WriteChunk(ctx, 0, req.Body) - if err != nil { - return &provider.ResourceInfo{}, errors.Wrap(err, "Decomposedfs: error writing to binary file") - } - session.SetSize(size) - } else { - size, err := session.WriteChunk(ctx, 0, req.Body) - if err != nil { - return &provider.ResourceInfo{}, errors.Wrap(err, "Decomposedfs: error writing to binary file") - } - if size != req.Length { - return &provider.ResourceInfo{}, errtypes.PartialContent("Decomposedfs: unexpected end of stream") - } - } - - if err := session.FinishUploadDecomposed(ctx); err != nil { - return &provider.ResourceInfo{}, err - } - - if uff != nil { - uploadRef := &provider.Reference{ - ResourceId: &provider.ResourceId{ - StorageId: session.ProviderID(), - SpaceId: session.SpaceID(), - OpaqueId: session.SpaceID(), - }, - Path: utils.MakeRelativePath(filepath.Join(session.Dir(), session.Filename())), - } - executant := session.Executant() - uff(session.SpaceOwner(), &executant, uploadRef) - } - - ri := &provider.ResourceInfo{ - // fill with at least fileid, mtime and etag - Id: &provider.ResourceId{ - StorageId: session.ProviderID(), - SpaceId: session.SpaceID(), - OpaqueId: session.NodeID(), - }, - } - - // add etag to metadata - ri.Etag, _ = node.CalculateEtag(session.NodeID(), session.MTime()) - - if !session.MTime().IsZero() { - ri.Mtime = utils.TimeToTS(session.MTime()) - } - - return ri, nil -} - -// InitiateUpload returns upload ids corresponding to different protocols it supports -// TODO read optional content for small files in this request -// TODO InitiateUpload (and Upload) needs a way to receive the expected checksum. Maybe in metadata as 'checksum' => 'sha1 aeosvp45w5xaeoe' = lowercase, space separated? -func (fs *Decomposedfs) InitiateUpload(ctx context.Context, ref *provider.Reference, uploadLength int64, metadata map[string]string) (map[string]string, error) { - _, span := tracer.Start(ctx, "InitiateUpload") - defer span.End() - log := appctx.GetLogger(ctx) - - // remember the path from the reference - refpath := ref.GetPath() - var chunk *chunking.ChunkBLOBInfo - var err error - if chunking.IsChunked(refpath) { // check chunking v1 - chunk, err = chunking.GetChunkBLOBInfo(refpath) - if err != nil { - return nil, errtypes.BadRequest(err.Error()) - } - ref.Path = chunk.Path - } - n, err := fs.lu.NodeFromResource(ctx, ref) - switch err.(type) { - case nil: - // ok - case errtypes.IsNotFound: - return nil, errtypes.PreconditionFailed(err.Error()) - default: - return nil, err - } - - // permissions are checked in NewUpload below - - relative, err := fs.lu.Path(ctx, n, node.NoCheck) - // TODO why do we need the path here? - // jfd: it is used later when emitting the UploadReady event ... - // AAAND refPath might be . when accessing with an id / relative reference ... which causes NodeName to become . But then dir will also always be . - // That is why we still have to read the path here: so that the event we emit contains a relative reference with a path relative to the space root. WTF - if err != nil { - return nil, err - } - - lockID, _ := ctxpkg.ContextGetLockID(ctx) - - session := fs.sessionStore.New(ctx) - session.SetMetadata("filename", n.Name) - session.SetStorageValue("NodeName", n.Name) - if chunk != nil { - session.SetStorageValue("Chunk", filepath.Base(refpath)) - } - session.SetMetadata("dir", filepath.Dir(relative)) - session.SetStorageValue("Dir", filepath.Dir(relative)) - session.SetMetadata("lockid", lockID) - - session.SetSize(uploadLength) - session.SetStorageValue("SpaceRoot", n.SpaceRoot.ID) // TODO SpaceRoot -> SpaceID - session.SetStorageValue("SpaceOwnerOrManager", n.SpaceOwnerOrManager(ctx).GetOpaqueId()) // TODO needed for what? - - spaceGID, ok := ctx.Value(CtxKeySpaceGID).(uint32) - if ok { - session.SetStorageValue("SpaceGid", fmt.Sprintf("%d", spaceGID)) - } - - iid, _ := ctxpkg.ContextGetInitiator(ctx) - session.SetMetadata("initiatorid", iid) - - if metadata != nil { - session.SetMetadata("providerID", metadata["providerID"]) - if mtime, ok := metadata["mtime"]; ok { - if mtime != "null" { - session.SetMetadata("mtime", metadata["mtime"]) - } - } - if expiration, ok := metadata["expires"]; ok { - if expiration != "null" { - session.SetMetadata("expires", metadata["expires"]) - } - } - if _, ok := metadata["sizedeferred"]; ok { - session.SetSizeIsDeferred(true) - } - if checksum, ok := metadata["checksum"]; ok { - parts := strings.SplitN(checksum, " ", 2) - if len(parts) != 2 { - return nil, errtypes.BadRequest("invalid checksum format. must be '[algorithm] [checksum]'") - } - switch parts[0] { - case "sha1", "md5", "adler32": - session.SetMetadata("checksum", checksum) - default: - return nil, errtypes.BadRequest("unsupported checksum algorithm: " + parts[0]) - } - } - - // only check preconditions if they are not empty // TODO or is this a bad request? - if metadata["if-match"] != "" { - session.SetMetadata("if-match", metadata["if-match"]) - } - if metadata["if-none-match"] != "" { - session.SetMetadata("if-none-match", metadata["if-none-match"]) - } - if metadata["if-unmodified-since"] != "" { - session.SetMetadata("if-unmodified-since", metadata["if-unmodified-since"]) - } - } - - if session.MTime().IsZero() { - session.SetMetadata("mtime", utils.TimeToOCMtime(time.Now())) - } - - log.Debug().Str("uploadid", session.ID()).Str("spaceid", n.SpaceID).Str("nodeid", n.ID).Interface("metadata", metadata).Msg("Decomposedfs: resolved filename") - - _, err = node.CheckQuota(ctx, n.SpaceRoot, n.Exists, uint64(n.Blobsize), uint64(session.Size())) - if err != nil { - return nil, err - } - - if session.Filename() == "" { - return nil, errors.New("Decomposedfs: missing filename in metadata") - } - if session.Dir() == "" { - return nil, errors.New("Decomposedfs: missing dir in metadata") - } - - // the parent owner will become the new owner - parent, perr := n.Parent(ctx) - if perr != nil { - return nil, errors.Wrap(perr, "Decomposedfs: error getting parent "+n.ParentID) - } - - // check permissions - var ( - checkNode *node.Node - path string - ) - if n.Exists { - // check permissions of file to be overwritten - checkNode = n - path, _ = storagespace.FormatReference(&provider.Reference{ResourceId: &provider.ResourceId{ - SpaceId: checkNode.SpaceID, - OpaqueId: checkNode.ID, - }}) - } else { - // check permissions of parent - checkNode = parent - path, _ = storagespace.FormatReference(&provider.Reference{ResourceId: &provider.ResourceId{ - SpaceId: checkNode.SpaceID, - OpaqueId: checkNode.ID, - }, Path: n.Name}) - } - rp, err := fs.p.AssemblePermissions(ctx, checkNode) - switch { - case err != nil: - return nil, err - case !rp.InitiateFileUpload: - return nil, errtypes.PermissionDenied(path) - } - - // are we trying to overwriting a folder with a file? - if n.Exists && n.IsDir(ctx) { - return nil, errtypes.PreconditionFailed("resource is not a file") - } - - // check lock - if err := n.CheckLock(ctx); err != nil { - return nil, err - } - - usr := ctxpkg.ContextMustGetUser(ctx) - - // fill future node info - if n.Exists { - if session.HeaderIfNoneMatch() == "*" { - return nil, errtypes.Aborted(fmt.Sprintf("parent %s already has a child %s, id %s", n.ParentID, n.Name, n.ID)) - } - session.SetStorageValue("NodeId", n.ID) - session.SetStorageValue("NodeExists", "true") - } else { - session.SetStorageValue("NodeId", uuid.New().String()) - } - session.SetStorageValue("NodeParentId", n.ParentID) - session.SetExecutant(usr) - session.SetStorageValue("LogLevel", log.GetLevel().String()) - - log.Debug().Interface("session", session).Msg("Decomposedfs: built session info") - - err = fs.um.RunInBaseScope(func() error { - // Create binary file in the upload folder with no content - // It will be used when determining the current offset of an upload - err := session.TouchBin() - if err != nil { - return err - } - - return session.Persist(ctx) - }) - if err != nil { - return nil, err - } - metrics.UploadSessionsInitiated.Inc() - - if uploadLength == 0 { - // Directly finish this upload - err = session.FinishUploadDecomposed(ctx) - if err != nil { - return nil, err - } - } - - return map[string]string{ - "simple": session.ID(), - "tus": session.ID(), - }, nil -} - -// UseIn tells the tus upload middleware which extensions it supports. -func (fs *Decomposedfs) UseIn(composer *tusd.StoreComposer) { - composer.UseCore(fs) - composer.UseTerminater(fs) - composer.UseConcater(fs) - composer.UseLengthDeferrer(fs) - composer.UseContentServer(fs) -} - -// To implement the core tus.io protocol as specified in https://tus.io/protocols/resumable-upload.html#core-protocol -// - the storage needs to implement NewUpload and GetUpload -// - the upload needs to implement the tusd.Upload interface: WriteChunk, GetInfo, GetReader and FinishUpload - -// NewUpload returns a new tus Upload instance -func (fs *Decomposedfs) NewUpload(_ context.Context, _ tusd.FileInfo) (tusd.Upload, error) { - return nil, fmt.Errorf("not implemented, use InitiateUpload on the CS3 API to start a new upload") -} - -// AsServableUpload returns a ServableUpload -// which implements the tusd.ServableUpload interface and -func (fs *Decomposedfs) AsServableUpload(u tusd.Upload) tusd.ServableUpload { - return u.(*upload.DecomposedFsSession) -} - -// GetUpload returns the Upload for the given upload id -func (fs *Decomposedfs) GetUpload(ctx context.Context, id string) (tusd.Upload, error) { - var ul tusd.Upload - var err error - _ = fs.um.RunInBaseScope(func() error { - ul, err = fs.sessionStore.Get(ctx, id) - return nil - }) - return ul, err -} - -// ResolveUpload stats the resource produced by a finished upload, reading it as the upload's -// executant. The session is reconstructed from the given tus FileInfo rather than the session -// store, so it still resolves after a synchronous upload has cleaned up its session. It returns -// the resource info and the executant context, so the caller can derive identity dependent -// values such as the WebDAV permissions. https://github.com/opencloud-eu/opencloud/issues/2409 -func (fs *Decomposedfs) ResolveUpload(ctx context.Context, info tusd.FileInfo) (*provider.ResourceInfo, context.Context, error) { - session := fs.sessionStore.SessionFromInfo(info) - ctx = session.Context(ctx) - ref := session.Reference() - ri, err := fs.GetMD(ctx, &ref, nil, nil) - return ri, ctx, err -} - -// ListUploadSessions returns the upload sessions for the given filter -func (fs *Decomposedfs) ListUploadSessions(ctx context.Context, filter storage.UploadSessionFilter) ([]storage.UploadSession, error) { - var sessions []*upload.DecomposedFsSession - if filter.ID != nil && *filter.ID != "" { - session, err := fs.sessionStore.Get(ctx, *filter.ID) - if err != nil { - return nil, err - } - sessions = []*upload.DecomposedFsSession{session} - } else { - var err error - sessions, err = fs.sessionStore.List(ctx) - if err != nil { - return nil, err - } - } - filteredSessions := []storage.UploadSession{} - now := time.Now() - for _, session := range sessions { - if filter.Processing != nil && *filter.Processing != session.IsProcessing() { - continue - } - if filter.Expired != nil { - if *filter.Expired { - if now.Before(session.Expires()) { - continue - } - } else { - if now.After(session.Expires()) { - continue - } - } - } - if filter.HasVirus != nil { - sr, _ := session.ScanData() - infected := sr != "" - if *filter.HasVirus != infected { - continue - } - } - filteredSessions = append(filteredSessions, session) - } - return filteredSessions, nil -} - -// AsTerminatableUpload returns a TerminatableUpload -// To implement the termination extension as specified in https://tus.io/protocols/resumable-upload.html#termination -// the storage needs to implement AsTerminatableUpload -func (fs *Decomposedfs) AsTerminatableUpload(up tusd.Upload) tusd.TerminatableUpload { - return up.(*upload.DecomposedFsSession) -} - -// AsLengthDeclarableUpload returns a LengthDeclarableUpload -// To implement the creation-defer-length extension as specified in https://tus.io/protocols/resumable-upload.html#creation -// the storage needs to implement AsLengthDeclarableUpload -func (fs *Decomposedfs) AsLengthDeclarableUpload(up tusd.Upload) tusd.LengthDeclarableUpload { - return up.(*upload.DecomposedFsSession) -} - -// AsConcatableUpload returns a ConcatableUpload -// To implement the concatenation extension as specified in https://tus.io/protocols/resumable-upload.html#concatenation -// the storage needs to implement AsConcatableUpload -func (fs *Decomposedfs) AsConcatableUpload(up tusd.Upload) tusd.ConcatableUpload { - return up.(*upload.DecomposedFsSession) +// IsOrphaned reports whether the referenced resource exists but its metadata is unreadable. +func (fs *Decomposedfs) IsOrphaned(ctx context.Context, ref *provider.Reference) bool { + _, err := fs.lu.NodeFromResource(ctx, ref) + return err != nil } diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/upload/session.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/upload/session.go deleted file mode 100644 index f6eb460ce9..0000000000 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/upload/session.go +++ /dev/null @@ -1,364 +0,0 @@ -// Copyright 2018-2023 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 upload - -import ( - "context" - "encoding/json" - "os" - "path/filepath" - "strconv" - "time" - - "github.com/google/renameio/v2" - tusd "github.com/tus/tusd/v2/pkg/handler" - - userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" - provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" - typespb "github.com/cs3org/go-cs3apis/cs3/types/v1beta1" - - "github.com/opencloud-eu/reva/v2/pkg/appctx" - ctxpkg "github.com/opencloud-eu/reva/v2/pkg/ctx" - "github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/node" - "github.com/opencloud-eu/reva/v2/pkg/utils" -) - -// DecomposedFsSession extends tus upload lifecycle with postprocessing steps. -type DecomposedFsSession struct { - store DecomposedFsStore - // for now, we keep the json files in the uploads folder - info tusd.FileInfo -} - -const ( - SessionStatusUploading = "uploading" - SessionStatusProcessing = "processing" - SessionStatusFailed = "failed" -) - -// Context returns a context with the user, logger and lockid used when initiating the upload session -func (session *DecomposedFsSession) Context(ctx context.Context) context.Context { // restore logger from file info - sub := session.store.log.With().Int("pid", os.Getpid()).Logger() - ctx = appctx.WithLogger(ctx, &sub) - ctx = ctxpkg.ContextSetLockID(ctx, session.lockID()) - ctx = ctxpkg.ContextSetUser(ctx, session.executantUser()) - return ctxpkg.ContextSetInitiator(ctx, session.InitiatorID()) -} - -func (session *DecomposedFsSession) lockID() string { - return session.info.MetaData["lockid"] -} -func (session *DecomposedFsSession) executantUser() *userpb.User { - var o *typespb.Opaque - _ = json.Unmarshal([]byte(session.info.Storage["UserOpaque"]), &o) - return &userpb.User{ - Id: &userpb.UserId{ - Type: userpb.UserType(userpb.UserType_value[session.info.Storage["UserType"]]), - Idp: session.info.Storage["Idp"], - OpaqueId: session.info.Storage["UserId"], - }, - Username: session.info.Storage["UserName"], - DisplayName: session.info.Storage["UserDisplayName"], - Opaque: o, - } -} - -// Purge deletes the upload session metadata and written binary data -func (session *DecomposedFsSession) Purge(ctx context.Context) { - _, span := tracer.Start(ctx, "Purge") - defer span.End() - session.Cleanup(true, true, true, true) -} - -// TouchBin creates a file to contain the binary data. It's size will be used to keep track of the tus upload offset. -func (session *DecomposedFsSession) TouchBin() error { - file, err := os.OpenFile(session.binPath(), os.O_CREATE|os.O_WRONLY, defaultFilePerm) - if err != nil { - return err - } - return file.Close() -} - -// Persist writes the upload session metadata to disk -// events can update the scan outcome and the finished event might read an empty file because of race conditions -// so we need to lock the file while writing and use atomic writes -func (session *DecomposedFsSession) Persist(ctx context.Context) error { - _, span := tracer.Start(ctx, "Persist") - defer span.End() - infoPath := session.infoPath() - // create folder structure (if needed) - if err := os.MkdirAll(filepath.Dir(infoPath), 0700); err != nil { - return err - } - - var d []byte - d, err := json.Marshal(session.info) - if err != nil { - return err - } - return renameio.WriteFile(infoPath, d, 0600) -} - -// ToFileInfo returns tus compatible FileInfo so the tus handler can access the upload offset -func (session *DecomposedFsSession) ToFileInfo() tusd.FileInfo { - return session.info -} - -// ProviderID returns the provider id -func (session *DecomposedFsSession) ProviderID() string { - return session.info.MetaData["providerID"] -} - -// SpaceID returns the space id -func (session *DecomposedFsSession) SpaceID() string { - return session.info.Storage["SpaceRoot"] -} - -// NodeID returns the node id -func (session *DecomposedFsSession) NodeID() string { - return session.info.Storage["NodeId"] -} - -// NodeParentID returns the nodes parent id -func (session *DecomposedFsSession) NodeParentID() string { - return session.info.Storage["NodeParentId"] -} - -// NodeExists returns wether or not the node existed during InitiateUpload. -// FIXME If two requests try to write the same file they both will store a new -// random node id in the session and try to initialize a new node when -// finishing the upload. The second request will fail with an already exists -// error when trying to create the symlink for the node in the parent directory. -// A node should be created as part of InitiateUpload. When listing a directory -// we can decide if we want to skip the entry, or expose uploed progress -// information. But that is a bigger change and might involve client work. -func (session *DecomposedFsSession) NodeExists() bool { - return session.info.Storage["NodeExists"] == "true" -} - -// HeaderIfMatch returns the if-match header for the upload session -func (session *DecomposedFsSession) HeaderIfMatch() string { - return session.info.MetaData["if-match"] -} - -// HeaderIfNoneMatch returns the if-none-match header for the upload session -func (session *DecomposedFsSession) HeaderIfNoneMatch() string { - return session.info.MetaData["if-none-match"] -} - -// HeaderIfUnmodifiedSince returns the if-unmodified-since header for the upload session -func (session *DecomposedFsSession) HeaderIfUnmodifiedSince() string { - return session.info.MetaData["if-unmodified-since"] -} - -// Node returns the node for the session -func (session *DecomposedFsSession) Node(ctx context.Context) (*node.Node, error) { - return node.ReadNode(ctx, session.store.lu, session.SpaceID(), session.info.Storage["NodeId"], "", false, nil, true) -} - -// ID returns the upload session id -func (session *DecomposedFsSession) ID() string { - return session.info.ID -} - -// Filename returns the name of the node which is not the same as the name af the file being uploaded for legacy chunked uploads -func (session *DecomposedFsSession) Filename() string { - return session.info.Storage["NodeName"] -} - -// Chunk returns the chunk name when a legacy chunked upload was started -func (session *DecomposedFsSession) Chunk() string { - return session.info.Storage["Chunk"] -} - -// SetMetadata is used to fill the upload metadata that will be exposed to the end user -func (session *DecomposedFsSession) SetMetadata(key, value string) { - session.info.MetaData[key] = value -} - -// SetStorageValue is used to set metadata only relevant for the upload session implementation -func (session *DecomposedFsSession) SetStorageValue(key, value string) { - session.info.Storage[key] = value -} - -// SetSize will set the upload size of the underlying tus info. -func (session *DecomposedFsSession) SetSize(size int64) { - session.info.Size = size -} - -// SetSizeIsDeferred is uset to change the SizeIsDeferred property of the underlying tus info. -func (session *DecomposedFsSession) SetSizeIsDeferred(value bool) { - session.info.SizeIsDeferred = value -} - -// Dir returns the directory to which the upload is made -// TODO get rid of Dir(), whoever consumes the reference should be able to deal -// with a relative reference. -// Dir is only used to: -// - fill the Path property when emitting the UploadReady event after -// postprocessing finished. I wonder why the UploadReady contains a finished -// flag ... maybe multiple distinct events would make more sense. -// - build the reference that is passed to the FileUploaded event in the -// UploadFinishedFunc callback passed to the Upload call used for simple -// datatx put requests -// -// AFAICT only search and audit services consume the path. -// - search needs to index from the root anyway. And it only needs the most -// recent path to put it in the index. So it should already be able to deal -// with an id based reference. -// - audit on the other hand needs to log events with the path at the state of -// the event ... so it does need the full path. -// -// I think we can safely determine the path later, right before emitting the -// event. And maybe make it configurable, because only audit needs it, anyway. -func (session *DecomposedFsSession) Dir() string { - return session.info.Storage["Dir"] -} - -// Size returns the upload size -func (session *DecomposedFsSession) Size() int64 { - return session.info.Size -} - -// SizeDiff returns the size diff that was calculated after postprocessing -func (session *DecomposedFsSession) SizeDiff() int64 { - sizeDiff, _ := strconv.ParseInt(session.info.MetaData["sizeDiff"], 10, 64) - return sizeDiff -} - -// Reference returns a reference that can be used to access the uploaded resource -func (session *DecomposedFsSession) Reference() provider.Reference { - return provider.Reference{ - ResourceId: &provider.ResourceId{ - StorageId: session.info.MetaData["providerID"], - SpaceId: session.info.Storage["SpaceRoot"], - OpaqueId: session.info.Storage["NodeId"], - }, - // Path is not used - } -} - -// Executant returns the id of the user that initiated the upload session -func (session *DecomposedFsSession) Executant() userpb.UserId { - return userpb.UserId{ - Type: userpb.UserType(userpb.UserType_value[session.info.Storage["UserType"]]), - Idp: session.info.Storage["Idp"], - OpaqueId: session.info.Storage["UserId"], - } -} - -// SetExecutant is used to remember the user that initiated the upload session -func (session *DecomposedFsSession) SetExecutant(u *userpb.User) { - session.info.Storage["Idp"] = u.GetId().GetIdp() - session.info.Storage["UserId"] = u.GetId().GetOpaqueId() - session.info.Storage["UserType"] = utils.UserTypeToString(u.GetId().Type) - session.info.Storage["UserName"] = u.GetUsername() - session.info.Storage["UserDisplayName"] = u.GetDisplayName() - - b, _ := json.Marshal(u.GetOpaque()) - session.info.Storage["UserOpaque"] = string(b) -} - -// Offset returns the current upload offset -func (session *DecomposedFsSession) Offset() int64 { - return session.info.Offset -} - -// SpaceOwner returns the id of the space owner -func (session *DecomposedFsSession) SpaceOwner() *userpb.UserId { - return &userpb.UserId{ - // idp and type do not seem to be consumed and the node currently only stores the user id anyway - OpaqueId: session.info.Storage["SpaceOwnerOrManager"], - } -} - -// Expires returns the time the upload session expires -func (session *DecomposedFsSession) Expires() time.Time { - var t time.Time - if value, ok := session.info.MetaData["expires"]; ok { - t, _ = utils.MTimeToTime(value) - } - return t -} - -// MTime returns the mtime to use for the uploaded file -func (session *DecomposedFsSession) MTime() time.Time { - var t time.Time - if value, ok := session.info.MetaData["mtime"]; ok { - t, _ = utils.MTimeToTime(value) - } - return t -} - -// IsProcessing returns true if the upload is in the processing state, meaning that the upload has finished and postprocessing is still running. -func (session *DecomposedFsSession) IsProcessing() bool { - return session.info.MetaData["status"] == SessionStatusProcessing -} - -// binPath returns the path to the file storing the binary data. -func (session *DecomposedFsSession) binPath() string { - return filepath.Join(session.store.root, "uploads", session.info.ID) -} - -// infoPath returns the path to the .info file storing the file's info. -func (session *DecomposedFsSession) infoPath() string { - return sessionPath(session.store.root, session.info.ID) -} - -// InitiatorID returns the id of the initiating client -func (session *DecomposedFsSession) InitiatorID() string { - return session.info.MetaData["initiatorid"] -} - -// SetScanData sets virus scan data to the upload session -func (session *DecomposedFsSession) SetScanData(result string, date time.Time) { - session.info.MetaData["scanResult"] = result - session.info.MetaData["scanDate"] = date.Format(time.RFC3339) -} - -// ScanData returns the virus scan data -func (session *DecomposedFsSession) ScanData() (string, time.Time) { - date := session.info.MetaData["scanDate"] - if date == "" { - return "", time.Time{} - } - d, _ := time.Parse(time.RFC3339, date) - return session.info.MetaData["scanResult"], d -} - -// SetStatus sets the status of the upload session -func (session *DecomposedFsSession) SetStatus(status, msg string) { - session.info.MetaData["status"] = status - session.info.MetaData["statusMessage"] = msg -} - -// Status returns the status of the upload session -func (session *DecomposedFsSession) Status() string { - return session.info.MetaData["status"] -} - -// StatusMessage returns the status message of the upload session -func (session *DecomposedFsSession) StatusMessage() string { - return session.info.MetaData["statusMessage"] -} - -// sessionPath returns the path to the .info file storing the file's info. -func sessionPath(root, id string) string { - return filepath.Join(root, "uploads", id+".info") -} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/upload/store.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/upload/store.go deleted file mode 100644 index 6de0976f47..0000000000 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/upload/store.go +++ /dev/null @@ -1,419 +0,0 @@ -// Copyright 2018-2022 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 upload - -import ( - "context" - "encoding/json" - "fmt" - iofs "io/fs" - "os" - "path/filepath" - "regexp" - "strconv" - "strings" - "syscall" - "time" - - provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" - "github.com/google/uuid" - "github.com/opencloud-eu/reva/v2/pkg/appctx" - "github.com/opencloud-eu/reva/v2/pkg/errtypes" - "github.com/opencloud-eu/reva/v2/pkg/events" - "github.com/opencloud-eu/reva/v2/pkg/storage" - "github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/aspects" - "github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/metadata" - "github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/metadata/prefixes" - "github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/node" - "github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/options" - "github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/usermapper" - "github.com/pkg/errors" - "github.com/rs/zerolog" - tusd "github.com/tus/tusd/v2/pkg/handler" -) - -var _idRegexp = regexp.MustCompile(".*/([^/]+).info") - -// PermissionsChecker defines an interface for checking permissions on a Node -type PermissionsChecker interface { - AssemblePermissions(ctx context.Context, n *node.Node) (ap provider.ResourcePermissions, err error) -} - -// DecomposedFsStore manages upload sessions -type DecomposedFsStore struct { - fs storage.FS - lu node.PathLookup - tp node.Tree - um usermapper.Mapper - root string - pub events.Publisher - async bool - tknopts options.TokenOptions - disableVersioning bool - log *zerolog.Logger -} - -// NewSessionStore returns a new DecomposedFsStore -func NewSessionStore(fs storage.FS, aspects aspects.Aspects, root string, async bool, tknopts options.TokenOptions, log *zerolog.Logger) *DecomposedFsStore { - return &DecomposedFsStore{ - fs: fs, - lu: aspects.Lookup, - tp: aspects.Tree, - root: root, - pub: aspects.EventStream, - async: async, - tknopts: tknopts, - disableVersioning: aspects.DisableVersioning, - um: aspects.UserMapper, - log: log, - } -} - -// New returns a new upload session -func (store DecomposedFsStore) New(ctx context.Context) *DecomposedFsSession { - return &DecomposedFsSession{ - store: store, - info: tusd.FileInfo{ - ID: uuid.New().String(), - Storage: map[string]string{ - "Type": "DecomposedFsStore", - }, - MetaData: tusd.MetaData{ - "status": string(SessionStatusUploading), - }, - }, - } -} - -// SessionFromInfo wraps an existing tus FileInfo into an upload session without reading the -// session store. It lets callers use an upload's session, e.g. its reference and -// executant context, after the store entry has already been cleaned up, as happens for a -// synchronous upload in its finish response callback. -func (store DecomposedFsStore) SessionFromInfo(info tusd.FileInfo) *DecomposedFsSession { - return &DecomposedFsSession{ - store: store, - info: info, - } -} - -// List lists all upload sessions -func (store DecomposedFsStore) List(ctx context.Context) ([]*DecomposedFsSession, error) { - uploads := []*DecomposedFsSession{} - infoFiles, err := filepath.Glob(filepath.Join(store.root, "uploads", "*.info")) - if err != nil { - return nil, err - } - - for _, info := range infoFiles { - id := strings.TrimSuffix(filepath.Base(info), filepath.Ext(info)) - progress, err := store.Get(ctx, id) - if err != nil { - appctx.GetLogger(ctx).Error().Interface("path", info).Msg("Decomposedfs: could not getUploadSession") - continue - } - - uploads = append(uploads, progress) - } - return uploads, nil -} - -// Get returns the upload session for the given upload id -func (store DecomposedFsStore) Get(ctx context.Context, id string) (*DecomposedFsSession, error) { - sessionPath := sessionPath(store.root, id) - match := _idRegexp.FindStringSubmatch(sessionPath) - if len(match) < 2 { - return nil, fmt.Errorf("invalid upload path") - } - - session := DecomposedFsSession{ - store: store, - info: tusd.FileInfo{}, - } - data, err := os.ReadFile(sessionPath) - if err != nil { - // handle stale NFS file handles that can occur when the file is deleted betwenn the ATTR and FOPEN call of os.ReadFile - if pathErr, ok := err.(*os.PathError); ok && pathErr.Err == syscall.ESTALE { - appctx.GetLogger(ctx).Info().Str("session", id).Err(err).Msg("treating stale file handle as not found") - err = tusd.ErrNotFound - } - if errors.Is(err, iofs.ErrNotExist) { - // Interpret os.ErrNotExist as 404 Not Found - err = tusd.ErrNotFound - } - return nil, err - } - - if err := json.Unmarshal(data, &session.info); err != nil { - return nil, err - } - - stat, err := os.Stat(session.binPath()) - if err != nil { - if os.IsNotExist(err) { - // Interpret os.ErrNotExist as 404 Not Found - err = tusd.ErrNotFound - } - return nil, err - } - - session.info.Offset = stat.Size() - - return &session, nil -} - -// Session is the interface used by the Cleanup call -type Session interface { - ID() string - Node(ctx context.Context) (*node.Node, error) - Context(ctx context.Context) context.Context - Cleanup(revertNodeMetadata, cleanBin, cleanInfo bool) -} - -// CreateNodeForUpload will create the target node for the Upload -// TODO move this to the node package as NodeFromUpload? -// should we in InitiateUpload create the node first? and then the upload? -func (store DecomposedFsStore) CreateNodeForUpload(ctx context.Context, session *DecomposedFsSession, initAttrs node.Attributes) (*node.Node, error) { - ctx, span := tracer.Start(session.Context(ctx), "CreateNodeForUpload") - defer span.End() - n := node.New( - session.SpaceID(), - session.NodeID(), - session.NodeParentID(), - session.Filename(), - session.Size(), - session.ID(), - provider.ResourceType_RESOURCE_TYPE_FILE, - nil, - store.lu, - ) - var err error - n.SpaceRoot, err = node.ReadNode(ctx, store.lu, session.SpaceID(), session.SpaceID(), "", false, nil, false) - if err != nil { - return nil, err - } - - // check lock - if err := n.CheckLock(ctx); err != nil { - return nil, err - } - - var unlock metadata.UnlockFunc - if session.NodeExists() { // TODO this is wrong. The node should be created when the upload starts, the revisions should be created independently of the node - // we do not need to propagate a change when a node is created, only when the upload is ready. - // that still creates problems for desktop clients because if another change causes propagation it will detects an empty file - // so the first upload has to point to the first revision with the expected size. The file cannot be downloaded, but it can be overwritten (which will create a new revision and make the node reflect the latest revision) - // any finished postprocessing will not affect the node metadata. - // *thinking* but then initializing an upload will lock the file until the upload has finished. That sucks. - // so we have to check if the node has been created meanwhile (well, only in case the upload does not know the nodeid ... or the NodeExists array that is checked by session.NodeExists()) - // FIXME look at the disk again to see if the file has been created in between, or just try initializing a new node and do the update existing node as a fallback. <- the latter! - - unlock, err = store.updateExistingNode(ctx, session, n, session.SpaceID(), uint64(session.Size())) - if err != nil { - appctx.GetLogger(ctx).Error().Err(err).Msg("failed to update existing node") - } - } else { - if c, ok := store.lu.(node.IDCacher); ok { - err := c.CacheID(ctx, n.SpaceID, n.ID, filepath.Join(n.ParentPath(), n.Name)) - if err != nil { - appctx.GetLogger(ctx).Error().Err(err).Msg("failed to cache id") - } - } - - unlock, err = store.tp.InitNewNode(ctx, n, uint64(session.Size())) - if err != nil { - appctx.GetLogger(ctx).Error().Str("path", n.InternalPath()).Err(err).Msg("failed to init new node") - } - session.info.MetaData["sizeDiff"] = strconv.FormatInt(session.Size(), 10) - } - defer func() { - if unlock == nil { - appctx.GetLogger(ctx).Info().Msg("did not get a unlockfunc, not unlocking") - return - } - - if err := unlock(); err != nil { - appctx.GetLogger(ctx).Error().Err(err).Str("nodeid", n.ID).Str("parentid", n.ParentID).Msg("could not close lock") - } - }() - if err != nil { - return nil, err - } - - // overwrite technical information - initAttrs.SetString(prefixes.IDAttr, n.ID) - initAttrs.SetInt64(prefixes.TypeAttr, int64(provider.ResourceType_RESOURCE_TYPE_FILE)) - initAttrs.SetString(prefixes.ParentidAttr, n.ParentID) - initAttrs.SetString(prefixes.NameAttr, n.Name) - initAttrs.SetString(prefixes.BlobIDAttr, n.BlobID) - initAttrs.SetInt64(prefixes.BlobsizeAttr, n.Blobsize) - initAttrs.SetString(prefixes.StatusPrefix, node.ProcessingStatus+session.ID()) - - // set mtime on the new node - mtime := time.Now() - if !session.MTime().IsZero() { - // overwrite mtime if requested - mtime = session.MTime() - } - err = store.lu.TimeManager().OverrideMtime(ctx, n, &initAttrs, mtime) - if err != nil { - return nil, errors.Wrap(err, "Decomposedfs: failed to set the mtime") - } - - // update node metadata with new blobid etc - err = n.SetXattrsWithContext(ctx, initAttrs) - if err != nil { - return nil, errors.Wrap(err, "Decomposedfs: could not write metadata") - } - - err = store.um.RunInBaseScope(func() error { - return session.Persist(ctx) - }) - if err != nil { - return nil, err - } - - return n, nil -} - -func (store DecomposedFsStore) updateExistingNode(ctx context.Context, session *DecomposedFsSession, n *node.Node, spaceID string, fsize uint64) (metadata.UnlockFunc, error) { - _, span := tracer.Start(ctx, "updateExistingNode") - defer span.End() - - // write lock existing node before reading any metadata - unlock, err := store.lu.MetadataBackend().Lock(n) - if err != nil { - return nil, err - } - - old, _ := node.ReadNode(ctx, store.lu, spaceID, n.ID, "", false, nil, false) - if _, err := node.CheckQuota(ctx, n.SpaceRoot, true, uint64(old.Blobsize), fsize); err != nil { - return unlock, err - } - - oldNodeMtime, err := old.GetMTime(ctx) - if err != nil { - return unlock, err - } - oldNodeEtag, err := node.CalculateEtag(old.ID, oldNodeMtime) - if err != nil { - return unlock, err - } - - // When the if-match header was set we need to check if the - // etag still matches before finishing the upload. - if session.HeaderIfMatch() != "" && session.HeaderIfMatch() != oldNodeEtag { - return unlock, errtypes.Aborted("etag mismatch") - } - - // When the if-none-match header was set we need to check if any of the - // etags matches before finishing the upload. - if session.HeaderIfNoneMatch() != "" { - if session.HeaderIfNoneMatch() == "*" { - return unlock, errtypes.Aborted("etag mismatch, resource exists") - } - for _, ifNoneMatchTag := range strings.Split(session.HeaderIfNoneMatch(), ",") { - if ifNoneMatchTag == oldNodeEtag { - return unlock, errtypes.Aborted("etag mismatch") - } - } - } - - // When the if-unmodified-since header was set we need to check if the - // etag still matches before finishing the upload. - if session.HeaderIfUnmodifiedSince() != "" { - ifUnmodifiedSince, err := time.Parse(time.RFC3339Nano, session.HeaderIfUnmodifiedSince()) - if err != nil { - return unlock, errtypes.InternalError(fmt.Sprintf("failed to parse if-unmodified-since time: %s", err)) - } - - if oldNodeMtime.After(ifUnmodifiedSince) { - return unlock, errtypes.Aborted("if-unmodified-since mismatch") - } - } - - if !store.disableVersioning { - span.AddEvent("CreateVersion") - timestamp := oldNodeMtime.UTC().Format(time.RFC3339Nano) - versionID := n.ID + node.RevisionIDDelimiter + timestamp - versionPath, err := session.store.tp.CreateRevision(ctx, n, timestamp) - if err != nil { - if !errors.Is(err, os.ErrExist) { - return unlock, err - } - - // a revision with this mtime does already exist. - // If the blobs are the same we can just delete the old one - versionNode := node.NewBaseNode(n.SpaceID, versionID, session.store.lu) - if err := validateChecksums(ctx, old, session, versionNode); err != nil { - return unlock, err - } - - // delete old blob - bID, _, err := session.store.lu.ReadBlobIDAndSizeAttr(ctx, versionNode, nil) - if err != nil { - return unlock, err - } - if err := session.store.tp.DeleteBlob(&node.Node{BaseNode: node.BaseNode{SpaceID: n.SpaceID}, BlobID: bID}); err != nil { - return unlock, err - } - - // clean revision file - if versionPath, err = session.store.tp.CreateRevision(ctx, n, timestamp); err != nil { - return unlock, err - } - } - - session.info.MetaData["versionID"] = versionID - // keep mtime from previous version - span.AddEvent("os.Chtimes") - if err := os.Chtimes(versionPath, oldNodeMtime, oldNodeMtime); err != nil { - return unlock, errtypes.InternalError(fmt.Sprintf("failed to change mtime of version node: %s", err)) - } - } - - session.info.MetaData["sizeDiff"] = strconv.FormatInt((int64(fsize) - old.Blobsize), 10) - - return unlock, nil -} - -func validateChecksums(ctx context.Context, n *node.Node, session *DecomposedFsSession, versionNode metadata.MetadataNode) error { - for _, t := range []string{"md5", "sha1", "adler32"} { - key := prefixes.ChecksumPrefix + t - - checksum, err := n.Xattr(ctx, key) - if err != nil { - return err - } - - revisionChecksum, err := session.store.lu.MetadataBackend().Get(ctx, versionNode, key) - if err != nil { - return err - } - - if string(checksum) == "" || string(revisionChecksum) == "" { - return errors.New("checksum not found") - } - - if string(checksum) != string(revisionChecksum) { - return errors.New("checksum mismatch") - } - } - - return nil -} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/upload/upload.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/upload/upload.go deleted file mode 100644 index 813c2e57f4..0000000000 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/upload/upload.go +++ /dev/null @@ -1,605 +0,0 @@ -// Copyright 2018-2022 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 upload - -import ( - "context" - "encoding/hex" - "fmt" - "hash" - "io" - "io/fs" - "net/http" - "os" - "strconv" - "strings" - "time" - - userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" - provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" - "github.com/golang-jwt/jwt/v5" - "github.com/pkg/errors" - tusd "github.com/tus/tusd/v2/pkg/handler" - "go.opentelemetry.io/otel" - "go.opentelemetry.io/otel/trace" - - "github.com/opencloud-eu/reva/v2/pkg/appctx" - ctxpkg "github.com/opencloud-eu/reva/v2/pkg/ctx" - "github.com/opencloud-eu/reva/v2/pkg/errtypes" - "github.com/opencloud-eu/reva/v2/pkg/events" - "github.com/opencloud-eu/reva/v2/pkg/rhttp/datatx/metrics" - "github.com/opencloud-eu/reva/v2/pkg/rhttp/datatx/utils/download" - "github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/disk" - "github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/metadata/prefixes" - "github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/node" - "github.com/opencloud-eu/reva/v2/pkg/utils" -) - -var ( - tracer trace.Tracer - defaultFilePerm = os.FileMode(0664) -) - -func init() { - tracer = otel.Tracer("github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/upload") -} - -// WriteChunk writes the stream from the reader to the given offset of the upload -func (session *DecomposedFsSession) WriteChunk(ctx context.Context, _ int64, src io.Reader) (int64, error) { - ctx, span := tracer.Start(session.Context(ctx), "WriteChunk") - defer span.End() - _, subspan := tracer.Start(ctx, "os.OpenFile") - file, err := os.OpenFile(session.binPath(), os.O_WRONLY|os.O_APPEND, defaultFilePerm) - subspan.End() - - log := appctx.GetLogger(ctx) - if err != nil { - log.Error().Err(err).Msg("WriteChunk: error opening upload file") - return 0, err - } - defer func() { - // sync the written chunk to disk. This ensures that the upload can be resumed, - // and helps to prevent issues with filesystem/journal freezes at the end of the upload - // when committing a large fsync operation on slow disks. - _ = disk.Fdatasync(file) - _ = file.Close() - }() - - // calculate cheksum here? needed for the TUS checksum extension. https://tus.io/protocols/resumable-upload.html#checksum - // TODO but how do we get the `Upload-Checksum`? WriteChunk() only has a context, offset and the reader ... - // It is sent with the PATCH request, well or in the POST when the creation-with-upload extension is used - // but the tus handler uses a context.Background() so we cannot really check the header and put it in the context ... - _, subspan = tracer.Start(ctx, "io.Copy") - n, err := io.Copy(file, src) - subspan.End() - - // If the HTTP PATCH request gets interrupted in the middle (e.g. because - // the user wants to pause the upload), Go's net/http returns an io.ErrUnexpectedEOF. - // However, for the decompsedfs driver it's not important whether the stream has ended - // on purpose or accidentally. - if err != nil && err != io.ErrUnexpectedEOF { - log.Error().Err(err).Msg("WriteChunk: error copying data to upload file") - return n, err - } - - // update upload.Session.Offset so subsequent code flow can use it. - // No need to persist the session as the offset is determined by stating the blob in the GetUpload / ReadSession codepath. - // The session offset is written to disk in FinishUpload - session.info.Offset += n - return n, nil -} - -// GetInfo returns the FileInfo -func (session *DecomposedFsSession) GetInfo(_ context.Context) (tusd.FileInfo, error) { - return session.ToFileInfo(), nil -} - -// GetReader returns an io.Reader for the upload -func (session *DecomposedFsSession) GetReader(ctx context.Context) (io.ReadCloser, error) { - _, span := tracer.Start(session.Context(ctx), "GetReader") - defer span.End() - return os.Open(session.binPath()) -} - -// FinishUpload finishes an upload and moves the file to the internal destination -// implements tusd.DataStore interface -// returns tusd errors -func (session *DecomposedFsSession) FinishUpload(ctx context.Context) error { - err := session.FinishUploadDecomposed(ctx) - - if err != nil { - // this is part of the tusd integration and we might be able to - // log the error in another place - log := appctx.GetLogger(ctx) - log.Error().Err(err).Msg("failed to finish upload") - } - - // we need to return a tusd error here to make the tusd handler return the correct status code - switch err.(type) { - case errtypes.AlreadyExists: - return tusd.NewError("ERR_ALREADY_EXISTS", err.Error(), http.StatusConflict) - case errtypes.Aborted: - return tusd.NewError("ERR_PRECONDITION_FAILED", err.Error(), http.StatusPreconditionFailed) - case errtypes.InsufficientStorage: - return tusd.NewError("ERR_INSUFFICIENT_STORAGE", err.Error(), http.StatusInsufficientStorage) - default: - return err - } -} - -// FinishUploadDecomposed finishes an upload and moves the file to the internal destination -// retures errtypes errors -func (session *DecomposedFsSession) FinishUploadDecomposed(ctx context.Context) error { - ctx, span := tracer.Start(session.Context(ctx), "FinishUpload") - defer span.End() - log := appctx.GetLogger(ctx) - - ctx = ctxpkg.ContextSetInitiator(ctx, session.InitiatorID()) - - ctx = context.WithoutCancel(ctx) // Do not cancel the finish process, we unconditionally want to complete the upload. - sha1h, md5h, adler32h, err := node.CalculateChecksums(ctx, session.binPath()) - if err != nil { - return err - } - - // compare if they match the sent checksum - // TODO the tus checksum extension would do this on every chunk, but I currently don't see an easy way to pass in the requested checksum. for now we do it in FinishUpload which is also called for chunked uploads - if session.info.MetaData["checksum"] != "" { - var err error - parts := strings.SplitN(session.info.MetaData["checksum"], " ", 2) - if len(parts) != 2 { - return errtypes.BadRequest("invalid checksum format. must be '[algorithm] [checksum]'") - } - switch parts[0] { - case "sha1": - err = checkHash(parts[1], sha1h) - case "md5": - err = checkHash(parts[1], md5h) - case "adler32": - err = checkHash(parts[1], adler32h) - default: - err = errtypes.BadRequest("unsupported checksum algorithm: " + parts[0]) - } - if err != nil { - session.Cleanup(false, true, true, false) - return err - } - } - - // update checksums - attrs := node.Attributes{ - prefixes.ChecksumPrefix + "sha1": sha1h.Sum(nil), - prefixes.ChecksumPrefix + "md5": md5h.Sum(nil), - prefixes.ChecksumPrefix + "adler32": adler32h.Sum(nil), - } - - // At this point we scope by the space to create the final file in the final location - if session.store.um != nil && session.info.Storage["SpaceGid"] != "" { - gid, err := strconv.Atoi(session.info.Storage["SpaceGid"]) - if err != nil { - return errors.Wrap(err, "failed to parse space gid") - } - - unscope, err := session.store.um.ScopeUserByIds(-1, gid) - if err != nil { - return errors.Wrap(err, "failed to scope user") - } - if unscope != nil { - defer func() { _ = unscope() }() - } - } - - n, err := session.store.CreateNodeForUpload(ctx, session, attrs) - if err != nil { - session.SetStatus(SessionStatusFailed, err.Error()) - if perr := session.Persist(ctx); perr != nil { - log.Error().Err(perr).Msg("failed to persist upload session after setting status to failed") - } - return err - } - - session.SetStatus(SessionStatusProcessing, "") - if err = session.Persist(ctx); err != nil { - log.Error().Err(err).Msg("failed to persist upload session after setting status to processing") - } - - // increase the processing counter for every started processing - // will be decreased in Cleanup() - metrics.UploadProcessing.Inc() - metrics.UploadSessionsBytesReceived.Inc() - - if session.store.pub != nil && session.info.Size > 0 { - u, _ := ctxpkg.ContextGetUser(ctx) - s, err := session.URL(ctx) - if err != nil { - return err - } - - var iu *userpb.User - if utils.ExistsInOpaque(u.Opaque, "impersonating-user") { - iu = &userpb.User{} - if err := utils.ReadJSONFromOpaque(u.Opaque, "impersonating-user", iu); err != nil { - return err - } - } - - if err := events.Publish(ctx, session.store.pub, events.BytesReceived{ - UploadID: session.ID(), - URL: s, - SpaceOwner: n.SpaceOwnerOrManager(session.Context(ctx)), - ExecutingUser: u, - ResourceID: &provider.ResourceId{SpaceId: n.SpaceID, OpaqueId: n.ID}, - Filename: session.Filename(), - Filesize: uint64(session.Size()), - ImpersonatingUser: iu, - }); err != nil { - return err - } - } - - // if the upload is synchronous or the upload is empty, finalize it now - // for 0-byte uploads we take a shortcut and finalize isn't called elsewhere - if !session.store.async || session.info.Size == 0 { - // handle postprocessing synchronously - err = session.Finalize(ctx) - session.Cleanup(err != nil, err == nil, true, true) - if err != nil { - log.Error().Err(err).Msg("failed to upload") - return err - } - metrics.UploadSessionsFinalized.Inc() - } - - return session.store.tp.Propagate(ctx, n, session.SizeDiff()) -} - -// Terminate terminates the upload -func (session *DecomposedFsSession) Terminate(_ context.Context) error { - session.Cleanup(true, true, true, true) - return nil -} - -// DeclareLength updates the upload length information -func (session *DecomposedFsSession) DeclareLength(ctx context.Context, length int64) error { - session.info.Size = length - session.info.SizeIsDeferred = false - return session.store.um.RunInBaseScope(func() error { - return session.Persist(session.Context(ctx)) - }) -} - -// ConcatUploads concatenates multiple uploads -func (session *DecomposedFsSession) ConcatUploads(_ context.Context, uploads []tusd.Upload) (err error) { - file, err := os.OpenFile(session.binPath(), os.O_WRONLY|os.O_APPEND, defaultFilePerm) - if err != nil { - return err - } - defer func() { - _ = file.Close() - }() - - for _, partialUpload := range uploads { - fileUpload := partialUpload.(*DecomposedFsSession) - - src, err := os.Open(fileUpload.binPath()) - if err != nil { - return err - } - defer func() { - _ = src.Close() - }() - - if _, err := io.Copy(file, src); err != nil { - return err - } - } - - return -} - -// Finalize finalizes the upload (eg moves the file to the internal destination) -func (session *DecomposedFsSession) Finalize(ctx context.Context) (err error) { - ctx, span := tracer.Start(session.Context(ctx), "Finalize") - defer span.End() - - n := node.New(session.SpaceID(), session.NodeID(), "", "", session.Size(), session.ID(), - provider.ResourceType_RESOURCE_TYPE_FILE, session.SpaceOwner(), session.store.lu) - - var ( - spaceRoot *node.Node - ) - switch spaceRoot, err = session.store.lu.NodeFromSpaceID(ctx, session.SpaceID()); { - case err != nil: - return fmt.Errorf("failed to get space root for space id %s: %v", session.SpaceID(), err) - case spaceRoot == nil: - return fmt.Errorf("space root for space id %s not found", session.SpaceID()) - case spaceRoot.InternalPath() == "": - return fmt.Errorf("space root for space id %s has no valid internal path", session.SpaceID()) - default: - n.SpaceRoot = spaceRoot - } - - // lock the node before reading its metadata and writing the blob - unlock, err := session.store.lu.MetadataBackend().Lock(n) - if err != nil { - return err - } - defer func() { - _ = unlock() - }() - - // Read the node attributes while holding the lock acquired above. - attribs, err := n.Xattrs(ctx) - if err != nil { - return err - } - status := attribs.String(prefixes.StatusPrefix) - isProcessing := strings.HasPrefix(status, node.ProcessingStatus) - processingID := strings.TrimPrefix(status, node.ProcessingStatus) - - // another upload on this node is in progress or has finished since we started - if !isProcessing || processingID != session.ID() { - // The node's current content is already this upload's content (e.g. a - // newer upload was reverted in the meantime) - no revision is needed, - // upload the blob to the node itself. - if attribs.String(prefixes.BlobIDAttr) == session.ID() { - appctx.GetLogger(ctx).Debug().Str("nodepath", n.InternalPath()).Msg("node already contains this upload's content, no revision needed") - } else { - versionID := n.ID + node.RevisionIDDelimiter + session.MTime().UTC().Format(time.RFC3339Nano) - // There should be a revision node (created by the other upload that finished before us), read it and upload our blob there. - existingRevisionNode, revisionNodeUnlock, err := node.LockAndReadNode(ctx, session.store.lu, session.SpaceID(), versionID, "", false, spaceRoot, false) - if err != nil || !existingRevisionNode.Exists { - // The revision node has not been created. Likely because the file on disk was modified externally and re-assilimated (watchfs == true) - // Let's create the revision node now and upload the blob to it. - n, revisionNodeUnlock, err = session.createRevisionNodeForUpload(ctx, n, session.MTime().UTC().Format(time.RFC3339Nano)) - if err != nil { - appctx.GetLogger(ctx).Debug().Err(err).Str("versionID", session.MTime().UTC().Format(time.RFC3339Nano)).Msg("failed to create revision node for upload finalization") - return err - } - } else { - n = existingRevisionNode - } - appctx.GetLogger(ctx).Debug().Str("new nodepath", n.InternalPath()).Msg("uploading to revision node, that was created for us by another upload") - defer func() { _ = revisionNodeUnlock() }() - } - } - - // upload the data to the blobstore - _, subspan := tracer.Start(ctx, "WriteBlob") - err = session.store.tp.WriteBlob(n, session.binPath()) - subspan.End() - if err != nil { - return errors.Wrap(err, "failed to upload file to blobstore") - } - - return nil -} - -func (session *DecomposedFsSession) createRevisionNodeForUpload(ctx context.Context, baseNode *node.Node, rev string) (*node.Node, func() error, error) { - versionID := baseNode.ID + node.RevisionIDDelimiter + rev - log := appctx.GetLogger(ctx) - _, err := session.store.tp.CreateRevision(ctx, baseNode, rev) - if err != nil { - log.Error().Err(err).Str("versionID", versionID).Msg("failed to create revision node for upload") - return nil, nil, err - } - - // FIXME: We already calculated the checksums in FinishUpload, we should maybe pass them via the session instead of recalculating them here - sha1h, md5h, adler32h, err := node.CalculateChecksums(ctx, session.binPath()) - if err != nil { - return nil, nil, err - } - - // update checksums - attrs := node.Attributes{ - prefixes.ChecksumPrefix + "sha1": sha1h.Sum(nil), - prefixes.ChecksumPrefix + "md5": md5h.Sum(nil), - prefixes.ChecksumPrefix + "adler32": adler32h.Sum(nil), - } - revisionNode, unlock, err := node.LockAndReadNode(ctx, session.store.lu, session.SpaceID(), versionID, "", false, baseNode.SpaceRoot, false) - if err == nil { - mtime := session.MTime() - attrs.SetString(prefixes.BlobIDAttr, session.ID()) - attrs.SetInt64(prefixes.BlobsizeAttr, session.Size()) - revisionNode.BlobID = session.ID() - revisionNode.Blobsize = session.Size() - - err = session.store.lu.TimeManager().OverrideMtime(ctx, revisionNode, &attrs, mtime) - if err != nil { - _ = unlock() - return nil, nil, errors.Wrap(err, "Decomposedfs: failed to set the mtime") - } - err = revisionNode.SetXattrsWithContext(ctx, attrs) - if err != nil { - _ = unlock() - return nil, nil, errors.Wrap(err, "Decomposedfs: failed to set node attributes") - } - } - return revisionNode, unlock, err -} - -func checkHash(expected string, h hash.Hash) error { - shash := hex.EncodeToString(h.Sum(nil)) - if expected != shash { - return errtypes.ChecksumMismatch(fmt.Sprintf("invalid checksum: expected %s got %x", expected, shash)) - } - return nil -} - -// cleanup cleans up after the upload is finished -func (session *DecomposedFsSession) Cleanup(revertNodeMetadata, cleanBin, cleanInfo, unmarkPostprocessing bool) { - ctx := session.Context(context.Background()) - sublog := session.store.log.With().Str("cleanup sessionid", session.ID()).Bool("revertNodeMetadata", revertNodeMetadata).Bool("cleanBin", cleanBin). - Bool("cleanInfo", cleanInfo).Bool("unmarkPostprocessing", unmarkPostprocessing).Logger() - - if revertNodeMetadata { - n, err := session.Node(ctx) - if err != nil { - sublog.Error().Err(err).Msg("reading node for session failed") - } else { - versionID := strings.TrimPrefix(session.info.MetaData["versionID"], n.ID+node.RevisionIDDelimiter) - if session.NodeExists() && versionID != "" { - sublog.Debug().Str("nodepath", n.InternalPath()).Str("versionID", versionID).Msg("restoring revision") - if err := n.RevertUpload(ctx, versionID); err != nil { - sublog.Error().Err(err).Str("versionID", versionID).Msg("reverting node metadata failed") - return - } - } else { - // if no other upload session is in progress (processing id != session id) or has finished (processing id == "") - latestSession, err := n.ProcessingID(ctx) - if err != nil { - sublog.Error().Err(err).Str("spaceid", n.SpaceID).Str("nodeid", n.ID).Str("uploadid", session.ID()).Msg("reading processingid for session failed") - } - if latestSession == session.ID() { - // actually delete the node - if err := n.Purge(ctx); err != nil { - sublog.Error().Err(err).Str("nodepath", n.InternalPath()).Msg("purging node failed") - } - } - // FIXME else if the upload has become a revision, delete the revision, or if it is the last one, delete the node - } - } - } - - if cleanBin { - if err := os.Remove(session.binPath()); err != nil && !errors.Is(err, fs.ErrNotExist) { - appctx.GetLogger(ctx).Error().Str("path", session.binPath()).Err(err).Msg("removing upload failed") - } - } - - if cleanInfo { - if err := os.Remove(session.infoPath()); err != nil { - sublog.Error().Err(err).Msg("removing upload info failed") - return - } - } - - if unmarkPostprocessing { - n, err := session.Node(ctx) - if err != nil { - sublog.Info().Err(err).Msg("could not read node") - return - } - // FIXME: after cleanup the node might already be deleted ... - if n != nil { // node can be nil when there was an error before it was created (eg. checksum-mismatch) - if err := n.UnmarkProcessing(ctx, session.ID()); err != nil { - sublog.Info().Err(err).Str("path", n.InternalPath()).Msg("unmarking processing failed") - } - } - } -} - -// URL returns a url to download an upload -func (session *DecomposedFsSession) URL(_ context.Context) (string, error) { - - u := joinurl(session.store.tknopts.DownloadEndpoint, "tus/", session.ID()) - if session.store.tknopts.DataGatewayEndpoint == "" { - return u, nil - } - - // we need to create a token - type transferClaims struct { - jwt.RegisteredClaims - Target string `json:"target"` - } - - ttl := time.Duration(session.store.tknopts.TransferExpires) * time.Second - claims := transferClaims{ - RegisteredClaims: jwt.RegisteredClaims{ - ExpiresAt: jwt.NewNumericDate(time.Now().Add(ttl)), - Audience: jwt.ClaimStrings{"reva"}, - IssuedAt: jwt.NewNumericDate(time.Now()), - }, - Target: u, - } - - t := jwt.NewWithClaims(jwt.GetSigningMethod("HS256"), claims) - - tkn, err := t.SignedString([]byte(session.store.tknopts.TransferSharedSecret)) - if err != nil { - return "", errors.Wrapf(err, "error signing token with claims %+v", claims) - } - - return joinurl(session.store.tknopts.DataGatewayEndpoint, tkn), nil -} - -// ServeContent serves the content of the upload and implements the http.ServeContent interface needed by tusd, -// it is used by the tusd handler to serve the content of the upload and supports range requests -func (session *DecomposedFsSession) ServeContent(ctx context.Context, w http.ResponseWriter, req *http.Request) error { - _, span := tracer.Start(session.Context(ctx), "ServeContent") - defer span.End() - - f, err := os.Open(session.binPath()) - if err != nil { - return err - } - defer func() { - _ = f.Close() - }() - - info, err := f.Stat() - if err != nil { - return err - } - - var r io.Reader = f - if err := func() error { - if req.Header.Get("Range") == "" { - return nil - } - - ranges, err := download.ParseRange(req.Header.Get("Range"), info.Size()) - switch { - case len(ranges) == 0: - fallthrough - case errors.Is(err, download.ErrInvalidRange): - // ignore invalid range and return the whole file - return nil - case err != nil: - return err - } - - r = io.NewSectionReader(f, ranges[0].Start, ranges[0].Length) - w.WriteHeader(http.StatusPartialContent) - w.Header().Set("Content-Range", ranges[0].ContentRange(info.Size())) - return nil - }(); err != nil { - return err - } - - if _, err := io.Copy(w, r); err != nil { - return err - } - - return nil -} - -// replace with url.JoinPath after switching to go1.19 -func joinurl(paths ...string) string { - var s strings.Builder - l := len(paths) - for i, p := range paths { - s.WriteString(p) - if !strings.HasSuffix(p, "/") && i != l-1 { - s.WriteString("/") - } - } - - return s.String() -} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/storage.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/storage.go index 7a44931400..6470293d61 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/storage.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/storage.go @@ -20,22 +20,105 @@ package storage import ( "context" + "errors" "io" "net/url" + "time" - user "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" + userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" registry "github.com/cs3org/go-cs3apis/cs3/storage/registry/v1beta1" - tusd "github.com/tus/tusd/v2/pkg/handler" ) -// MoveResult carries the resolved references returned by a successful Move. type MoveResult struct { - SpaceOwner *user.UserId + SpaceOwner *userpb.UserId OldReference *provider.Reference NewReference *provider.Reference } +type UploadChecksums struct { + SHA1 []byte + MD5 []byte + Adler32 []byte +} + +// ErrSourceNotStored is wrapped by the error PrepareUpload returns when it could +// not store UploadInfo.Source. The node is unchanged and the staged bytes are +// still the only copy of the upload. +var ErrSourceNotStored = errors.New("could not store the upload source") + +type UploadInfo struct { + NodeExisted bool // true when the target node existed before the upload started + Size int64 + MTime time.Time + Checksums UploadChecksums + IfMatch string + IfNoneMatch string + IfUnmodifiedSince time.Time + // Where a new file goes, for a driver whose PrepareUpload creates it. Empty + // leaves a missing node NotFound. + ParentID string + Name string + // Source carries the staged bytes when the upload is finished right away, + // without postprocessing. A driver that can store them before the node + // points to them does so, leaves the node unmarked and reports Committed. + // Any other driver ignores it and gets CommitUpload as usual. + Source *UploadSource +} + +type PrepareUploadResult struct { + VersionCreated bool + SizeDiff int64 + SpaceOwner *userpb.UserId // the space owner or a manager, for a new node; nil keeps the one already known + // Committed reports that PrepareUpload stored UploadInfo.Source: the upload + // is complete, and neither CommitUpload nor MarkProcessing must follow. + Committed bool +} + +// RollbackInfo carries what a driver needs to undo PrepareUpload. NodeID and +// ParentID come from the upload session rather than the node, so a rollback can +// still release the quota of a node whose own metadata has become unreadable. +type RollbackInfo struct { + NodeExisted bool // true when the target node had a prior version; drivers with nothing to undo for new nodes may no-op + SizeDiff int64 + NodeID string + ParentID string + Filename string + Size int64 +} + +type CreateDirResult struct { + SpaceOwner *userpb.UserId + SpaceID string + ResourceID *provider.ResourceId +} + +type TouchFileResult struct { + SpaceOwner *userpb.UserId + SpaceID string + ResourceID *provider.ResourceId +} + +type RestoreRevisionResult struct { + SpaceOwner *userpb.UserId + SpaceID string +} + +type RestoreRecycleItemResult struct { + SpaceOwner *userpb.UserId + SpaceID string +} + +type SetLockResult struct { + SpaceOwner *userpb.UserId + SpaceID string +} + +type UnlockResult struct { + SpaceOwner *userpb.UserId + SpaceID string +} + // FS is the interface to implement access to the storage. type FS interface { // Minimal set for a readonly storage driver @@ -67,27 +150,37 @@ type FS interface { // CreateReference creates a resource of type reference CreateReference(ctx context.Context, path string, targetURI *url.URL) error // CreateDir creates a resource of type container - CreateDir(ctx context.Context, ref *provider.Reference) error + CreateDir(ctx context.Context, ref *provider.Reference) (*CreateDirResult, error) // TouchFile sets the mtime of a resource, creating an empty file if it does not exist - // FIXME(OCISDEV-900) remove markprocessing bool: coordinator calls MarkProcessing(true) explicitly after TouchFile + // FIXME(OCISDEV-900) remove markprocessing bool: PrepareUpload marks the node the coordinator touched // FIXME the mtime should either be a time.Time or a CS3 Timestamp, not a string - TouchFile(ctx context.Context, ref *provider.Reference, markprocessing bool, mtime string) error + TouchFile(ctx context.Context, ref *provider.Reference, markprocessing bool, mtime string) (*TouchFileResult, error) // Delete deletes a resource. - // If the storage driver supports a recycle bin it should moves it to the recycle bin - Delete(ctx context.Context, ref *provider.Reference) error + // If the storage driver supports a recycle bin it should move it to the recycle bin + // On success, returns a DeleteResult used by the wrapper to publish ItemTrashed. + Delete(ctx context.Context, ref *provider.Reference) (*DeleteResult, error) // Move changes the path of a resource and returns resolved references and the // space owner for event publication. Drivers without this metadata may return // a nil result on success. Move(ctx context.Context, oldRef, newRef *provider.Reference) (*MoveResult, error) - // InitiateUpload returns a list of protocols with urls that can be used to append bytes to a new upload session - InitiateUpload(ctx context.Context, ref *provider.Reference, uploadLength int64, metadata map[string]string) (map[string]string, error) - // Upload creates or updates a resource of type file with a new revision - Upload(ctx context.Context, req UploadRequest, uploadFunc UploadFinishedFunc) (*provider.ResourceInfo, error) // MarkProcessing toggles a processing flag on the resource. MarkProcessing(ctx context.Context, ref *provider.Reference, processing bool, sessionID string) error // CommitUpload writes the staged bytes from source to the resource at ref. - // Caller owns source.Body and must close it after CommitUpload returns. + // source carries a Body, a Path or both. Caller owns source.Body and must close it + // after CommitUpload returns. CommitUpload(ctx context.Context, ref *provider.Reference, sessionID string, source UploadSource) error + // PrepareUpload is called after all bytes are received and before postprocessing begins. + // Implementations may lock the target node, snapshot the previous version, write new metadata, + // mark the node as processing for sessionID, and propagate size changes. Drivers that do not + // require any of these steps may return immediately. + PrepareUpload(ctx context.Context, ref *provider.Reference, sessionID string, info UploadInfo) (*PrepareUploadResult, error) + // RollbackUpload reverts node state after a failed or aborted postprocessing run. + // It is the inverse of PrepareUpload: restores previous metadata and reverts the optimistic + // size propagation. The caller (coordinator) is responsible for unmarking the processing flag + // and deleting the upload session files. Drivers that performed no work in PrepareUpload may return nil. + // Callers must keep the session on a returned error: the rollback is retryable and info + // carries state the driver cannot recover once the session files are gone. + RollbackUpload(ctx context.Context, ref *provider.Reference, sessionID string, info RollbackInfo) error // Revisions @@ -96,7 +189,7 @@ type FS interface { // DownloadRevision downloads a revision DownloadRevision(ctx context.Context, ref *provider.Reference, key string, openReaderFunc func(md *provider.ResourceInfo) bool) (*provider.ResourceInfo, io.ReadCloser, error) // RestoreRevision restores a revision - RestoreRevision(ctx context.Context, ref *provider.Reference, key string) error + RestoreRevision(ctx context.Context, ref *provider.Reference, key string) (*RestoreRevisionResult, error) // Recyce bin @@ -104,7 +197,7 @@ type FS interface { ListRecycle(ctx context.Context, ref *provider.Reference, key, relativePath string) ([]*provider.RecycleItem, error) // RestoreRecycleItem restores an item from the recyle bin // if restoreRef is nil the resource should be restored at the original path - RestoreRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string, restoreRef *provider.Reference) error + RestoreRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string, restoreRef *provider.Reference) (*RestoreRecycleItemResult, error) // PurgeRecycleItem removes a resource from the recycle bin PurgeRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string) error // EmptyRecycle removes all resource from the recycle bin @@ -132,20 +225,20 @@ type FS interface { UnsetArbitraryMetadata(ctx context.Context, ref *provider.Reference, keys []string) error // AddLabel adds a label to a resource - AddLabel(ctx context.Context, ref *provider.Reference, userID *user.UserId, label string) error + AddLabel(ctx context.Context, ref *provider.Reference, userID *userpb.UserId, label string) error // RemoveLabel removes a label from a resource - RemoveLabel(ctx context.Context, ref *provider.Reference, userID *user.UserId, label string) error + RemoveLabel(ctx context.Context, ref *provider.Reference, userID *userpb.UserId, label string) error // Locks // GetLock returns an existing lock on the given reference GetLock(ctx context.Context, ref *provider.Reference) (*provider.Lock, error) // SetLock puts a lock on the given reference - SetLock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) error + SetLock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) (*SetLockResult, error) // RefreshLock refreshes an existing lock on the given reference RefreshLock(ctx context.Context, ref *provider.Reference, lock *provider.Lock, existingLockID string) error // Unlock removes an existing lock from the given reference - Unlock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) error + Unlock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) (*UnlockResult, error) // Spaces @@ -153,8 +246,10 @@ type FS interface { CreateStorageSpace(ctx context.Context, req *provider.CreateStorageSpaceRequest) (*provider.CreateStorageSpaceResponse, error) // UpdateStorageSpace updates a storage space UpdateStorageSpace(ctx context.Context, req *provider.UpdateStorageSpaceRequest) (*provider.UpdateStorageSpaceResponse, error) - // DeleteStorageSpace deletes a storage space - DeleteStorageSpace(ctx context.Context, req *provider.DeleteStorageSpaceRequest) error + // DeleteStorageSpace deletes a storage space. + // On a successful delete (purge), returns a DeleteStorageSpaceResult used by + // the wrapper to publish SpaceDeleted. SpaceDisabled does not need this data. + DeleteStorageSpace(ctx context.Context, req *provider.DeleteStorageSpaceRequest) (*DeleteStorageSpaceResult, error) // CreateHome creates a users home // @@ -176,15 +271,77 @@ type SpaceDisabledListableFS interface { type UploadSource struct { Body io.ReadCloser Length int64 + // Path is the staged file, if the caller has one. Drivers may move it into + // place instead of copying Body; the file is gone after a successful commit. + Path string + + // ScanResult is the antivirus verdict: empty means clean. + ScanResult string + // ScanDate is zero when the upload was not scanned. + ScanDate time.Time +} + +// DeleteResult is returned by FS.Delete on success. It carries the data the +// storageprovider wrapper needs to publish the ItemTrashed event. +type DeleteResult struct { + // SpaceOwner is the owner of the space the deleted resource belonged to. + SpaceOwner *userpb.UserId + // ResourceId is the stable identifier of the deleted resource, used as ItemTrashed.ID in the published event. + ResourceId *provider.ResourceId +} + +// DeleteStorageSpaceResult is returned by FS.DeleteStorageSpace on a successful +// purge. It carries the data the storageprovider wrapper needs to publish the +// SpaceDeleted event. The SpaceDisabled flow does not consume it. +type DeleteStorageSpaceResult struct { + // SpaceName is the name of the space at the time of deletion. + SpaceName string + // FinalMembers is the grant map of the space at the time of deletion, + // keyed by user/group opaque id. + FinalMembers map[string]provider.ResourcePermissions } // UnscopeFunc is a function that unscopes a user type UnscopeFunc func() -// Composable is the interface that a struct needs to implement -// to be composable, so that it can support the TUS methods -type ComposableFS interface { - UseIn(composer *tusd.StoreComposer) +// CapabilitiesOpaqueKey is the StorageSpace/ProviderInfo Opaque key under which +// a provider's Capabilities are carried as JSON up to the OCS capabilities handler. +const CapabilitiesOpaqueKey = "storage-capabilities" + +// Capabilities is a storage driver's self-declaration of the write-shaped +// actions it supports. A false key means unsupported: no merge, no inheritance. +type Capabilities struct { + Upload bool + CreateContainer bool + Delete bool + Move bool + Versioning bool + Trash bool + Locking bool + Sharing bool + ArbitraryMetadata bool +} + +// FullCapabilities is the default for drivers that do not implement +// CapabilityProvider, so existing drivers keep their current behavior. +func FullCapabilities() Capabilities { + return Capabilities{ + Upload: true, + CreateContainer: true, + Delete: true, + Move: true, + Versioning: true, + Trash: true, + Locking: true, + Sharing: true, + ArbitraryMetadata: true, + } +} + +// CapabilityProvider is an optional interface a storage.FS may implement to +// declare its capabilities. +type CapabilityProvider interface { + Capabilities(ctx context.Context) Capabilities } // Registry is the interface that storage registries implement diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/uploads.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/uploads.go index 880739ef9e..01fd08e83f 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/uploads.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/uploads.go @@ -20,7 +20,6 @@ package storage import ( "context" - "io" "time" userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" @@ -28,28 +27,17 @@ import ( tusd "github.com/tus/tusd/v2/pkg/handler" ) -// UploadFinishedFunc is a callback function used in storage drivers to indicate that an upload has finished -type UploadFinishedFunc func(spaceOwner, executant *userpb.UserId, ref *provider.Reference) +type skipTouchPropagationKey struct{} -// UploadRequest us used in FS.Upload() to carry required upload metadata -type UploadRequest struct { - Ref *provider.Reference - Body io.ReadCloser - Length int64 +// ContextSkipTouchPropagation tells TouchFile not to propagate. +func ContextSkipTouchPropagation(ctx context.Context) context.Context { + return context.WithValue(ctx, skipTouchPropagationKey{}, true) } -// UploadsManager defines the interface for storage drivers that allow for managing uploads -// -// Deprecated: No longer used. Storage drivers should implement the UploadSessionLister. -type UploadsManager interface { - ListUploads() ([]tusd.FileInfo, error) - PurgeExpiredUploads(chan<- tusd.FileInfo) error -} - -// UploadSessionLister defines the interface for FS implementations that allow listing and purging upload sessions -type UploadSessionLister interface { - // ListUploadSessions returns the upload sessions matching the given filter - ListUploadSessions(ctx context.Context, filter UploadSessionFilter) ([]UploadSession, error) +// SkipTouchPropagation reports whether TouchFile should skip propagation. +func SkipTouchPropagation(ctx context.Context) bool { + skip, _ := ctx.Value(skipTouchPropagationKey{}).(bool) + return skip } // UploadSessionResolver defines the interface for FS implementations that can resolve a finished @@ -66,6 +54,20 @@ type UploadSessionResolver interface { ResolveUpload(ctx context.Context, info tusd.FileInfo) (*provider.ResourceInfo, context.Context, error) } +// OrphanChecker defines the interface for FS implementations that can resolve a resource's metadata. +type OrphanChecker interface { + // IsOrphaned reports whether the referenced resource exists but its metadata is unreadable. + IsOrphaned(ctx context.Context, ref *provider.Reference) bool +} + +// NodeCreator defines the interface for FS implementations whose PrepareUpload +// creates a new file's node from UploadInfo.ParentID and Name, so an upload need +// not TouchFile it first. +type NodeCreator interface { + // PrepareCreatesNode reports whether PrepareUpload creates a missing node. + PrepareCreatesNode() bool +} + // UploadSession is the interface that storage drivers need to return whan listing upload sessions. type UploadSession interface { // ID returns the upload id @@ -107,4 +109,8 @@ type UploadSessionFilter struct { Processing *bool Expired *bool HasVirus *bool + // Orphaned filters sessions by whether their target node can still be + // resolved. Evaluating it requires reading the node metadata of every + // session, so it is only evaluated when set. + Orphaned *bool } diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/chunking/chunking.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/chunking/chunking.go index 80513937a9..228ee96510 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/chunking/chunking.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/chunking/chunking.go @@ -201,6 +201,45 @@ func (c *ChunkHandler) saveChunk(path string, r io.ReadCloser) (bool, string, er return true, assembledFileName, nil } +// Assemble saves an intermediate chunk and, once all chunks have arrived, +// assembles them into a single temp file. Returns (reader, size, true, nil) +// when the transfer is complete. Returns (nil, 0, false, nil) when more +// chunks are still expected (partial transfer) +// the returned reader removes the temp file on Close +func (c *ChunkHandler) Assemble(chunkName string, body io.ReadCloser) (io.ReadCloser, int64, bool, error) { + origPath, assembledPath, err := c.WriteChunk(chunkName, body) + if err != nil { + return nil, 0, false, err + } + if origPath == "" { + return nil, 0, false, nil // partial + } + f, err := os.Open(assembledPath) + if err != nil { + _ = os.RemoveAll(assembledPath) + return nil, 0, false, err + } + fi, err := f.Stat() + if err != nil { + _ = f.Close() + _ = os.RemoveAll(assembledPath) + return nil, 0, false, err + } + return &assembledFile{File: f, path: assembledPath}, fi.Size(), true, nil +} + +// assembledFile wraps an *os.File and removes the temp file on Close. +type assembledFile struct { + *os.File + path string +} + +func (a *assembledFile) Close() error { + err := a.File.Close() + _ = os.RemoveAll(a.path) + return err +} + // WriteChunk saves an intermediate chunk temporarily and assembles all chunks // once the final one is received. func (c *ChunkHandler) WriteChunk(fn string, r io.ReadCloser) (string, string, error) { diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/eosfs/eosfs.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/eosfs/eosfs.go index aaaf79b47b..73c840b85c 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/eosfs/eosfs.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/eosfs/eosfs.go @@ -788,36 +788,36 @@ func (fs *eosfs) setLock(ctx context.Context, lock *provider.Lock, path string, } // SetLock puts a lock on the given reference -func (fs *eosfs) SetLock(ctx context.Context, ref *provider.Reference, l *provider.Lock) error { +func (fs *eosfs) SetLock(ctx context.Context, ref *provider.Reference, l *provider.Lock) (*storage.SetLockResult, error) { if l.Type == provider.LockType_LOCK_TYPE_SHARED { - return errtypes.NotSupported("shared lock not yet implemented") + return nil, errtypes.NotSupported("shared lock not yet implemented") } path, err := fs.resolve(ctx, ref) if err != nil { - return errors.Wrap(err, "eosfs: error resolving reference") + return nil, errors.Wrap(err, "eosfs: error resolving reference") } path = fs.wrap(ctx, path) user, err := getUser(ctx) if err != nil { - return errors.Wrap(err, "eosfs: no user in ctx") + return nil, errors.Wrap(err, "eosfs: no user in ctx") } auth, err := fs.getUserAuth(ctx, user, path) if err != nil { - return errors.Wrap(err, "eosfs: error getting uid and gid for user") + return nil, errors.Wrap(err, "eosfs: error getting uid and gid for user") } _, err = fs.getLock(ctx, auth, user, path, ref) if err != nil { // if the err is NotFound it is fine, otherwise we have to return if _, ok := err.(errtypes.NotFound); !ok { - return err + return nil, err } } if err == nil { // the resource is already locked - return errtypes.BadRequest("resource already locked") + return nil, errtypes.BadRequest("resource already locked") } // the cs3apis require to have the write permission on the resource @@ -826,10 +826,10 @@ func (fs *eosfs) SetLock(ctx context.Context, ref *provider.Reference, l *provid // the request has it has, err := fs.userHasWriteAccess(ctx, user, ref) if err != nil { - return errors.Wrap(err, fmt.Sprintf("eosfs: cannot check if user %s has write access on resource", user.Username)) + return nil, errors.Wrap(err, fmt.Sprintf("eosfs: cannot check if user %s has write access on resource", user.Username)) } if !has { - return errtypes.PermissionDenied(fmt.Sprintf("user %s has not write access on resource", user.Username)) + return nil, errtypes.PermissionDenied(fmt.Sprintf("user %s has not write access on resource", user.Username)) } // the user in the lock could differ from the user in the context @@ -837,14 +837,17 @@ func (fs *eosfs) SetLock(ctx context.Context, ref *provider.Reference, l *provid if l.User != nil && !utils.UserEqual(user.Id, l.User) { has, err := fs.userIDHasWriteAccess(ctx, l.User, ref) if err != nil { - return errors.Wrap(err, "eosfs: cannot check if user has write access on resource") + return nil, errors.Wrap(err, "eosfs: cannot check if user has write access on resource") } if !has { - return errtypes.PermissionDenied(fmt.Sprintf("user %s has not write access on resource", user.Username)) + return nil, errtypes.PermissionDenied(fmt.Sprintf("user %s has not write access on resource", user.Username)) } } - return fs.setLock(ctx, l, path, true) + if err := fs.setLock(ctx, l, path, true); err != nil { + return nil, err + } + return &storage.SetLockResult{}, nil } func (fs *eosfs) getUserFromID(ctx context.Context, userID *userpb.UserId) (*userpb.User, error) { @@ -960,9 +963,9 @@ func sameHolder(l1, l2 *provider.Lock) bool { } // Unlock removes an existing lock from the given reference -func (fs *eosfs) Unlock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) error { +func (fs *eosfs) Unlock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) (*storage.UnlockResult, error) { if lock.Type == provider.LockType_LOCK_TYPE_SHARED { - return errtypes.NotSupported("shared lock not yet implemented") + return nil, errtypes.NotSupported("shared lock not yet implemented") } oldLock, err := fs.GetLock(ctx, ref) @@ -970,47 +973,50 @@ func (fs *eosfs) Unlock(ctx context.Context, ref *provider.Reference, lock *prov switch err.(type) { case errtypes.NotFound: // the lock does not exist - return errtypes.BadRequest("file was not locked") + return nil, errtypes.BadRequest("file was not locked") default: - return err + return nil, err } } // check if the lock id of the lock corresponds to the stored lock if oldLock.LockId != lock.LockId { - return errtypes.BadRequest("lock id does not match") + return nil, errtypes.BadRequest("lock id does not match") } if !sameHolder(oldLock, lock) { - return errtypes.BadRequest("caller does not hold the lock") + return nil, errtypes.BadRequest("caller does not hold the lock") } user, err := getUser(ctx) if err != nil { - return errors.Wrap(err, "eosfs: error getting user") + return nil, errors.Wrap(err, "eosfs: error getting user") } // the cs3apis require to have the write permission on the resource // to remove the lock has, err := fs.userHasWriteAccess(ctx, user, ref) if err != nil { - return errors.Wrap(err, "eosfs: cannot check if user has write access on resource") + return nil, errors.Wrap(err, "eosfs: cannot check if user has write access on resource") } if !has { - return errtypes.PermissionDenied(fmt.Sprintf("user %s has not write access on resource", user.Username)) + return nil, errtypes.PermissionDenied(fmt.Sprintf("user %s has not write access on resource", user.Username)) } path, err := fs.resolve(ctx, ref) if err != nil { - return errors.Wrap(err, "eosfs: error resolving reference") + return nil, errors.Wrap(err, "eosfs: error resolving reference") } path = fs.wrap(ctx, path) auth, err := fs.getRootAuth(ctx) if err != nil { - return errors.Wrap(err, "eosfs: error getting uid and gid for user") + return nil, errors.Wrap(err, "eosfs: error getting uid and gid for user") } - return fs.removeLockAttrs(ctx, auth, path) + if err := fs.removeLockAttrs(ctx, auth, path); err != nil { + return nil, err + } + return &storage.UnlockResult{}, nil } func (fs *eosfs) AddGrant(ctx context.Context, ref *provider.Reference, g *provider.Grant) error { @@ -1650,44 +1656,49 @@ func (fs *eosfs) createUserDir(ctx context.Context, u *userpb.User, path string, return nil } -func (fs *eosfs) CreateDir(ctx context.Context, ref *provider.Reference) error { +func (fs *eosfs) CreateDir(ctx context.Context, ref *provider.Reference) (*storage.CreateDirResult, error) { log := appctx.GetLogger(ctx) p, err := fs.resolve(ctx, ref) if err != nil { - return errors.Wrap(err, "eosfs: error resolving reference") + return nil, errors.Wrap(err, "eosfs: error resolving reference") } if fs.isShareFolder(ctx, p) { - return errtypes.PermissionDenied("eosfs: cannot perform operation under the virtual share folder") + return nil, errtypes.PermissionDenied("eosfs: cannot perform operation under the virtual share folder") } fn := fs.wrap(ctx, p) u, err := getUser(ctx) if err != nil { - return errors.Wrap(err, "eosfs: no user in ctx") + return nil, errors.Wrap(err, "eosfs: no user in ctx") } // We need the auth corresponding to the parent directory // as the file might not exist at the moment auth, err := fs.getUserAuth(ctx, u, path.Dir(fn)) if err != nil { - return err + return nil, err } log.Info().Msgf("eosfs: createdir: path=%s", fn) - return fs.c.CreateDir(ctx, auth, fn) + if err := fs.c.CreateDir(ctx, auth, fn); err != nil { + return nil, err + } + return &storage.CreateDirResult{}, nil } // TouchFile as defined in the storage.FS interface -func (fs *eosfs) TouchFile(ctx context.Context, ref *provider.Reference, _ bool, _ string) error { +func (fs *eosfs) TouchFile(ctx context.Context, ref *provider.Reference, _ bool, _ string) (*storage.TouchFileResult, error) { log := appctx.GetLogger(ctx) fn, auth, err := fs.resolveRefAndGetAuth(ctx, ref) if err != nil { - return err + return nil, err } log.Info().Msgf("eosfs: touch file: path=%s", fn) - - return fs.c.Touch(ctx, auth, fn) + if err := fs.c.Touch(ctx, auth, fn); err != nil { + return nil, err + } + return &storage.TouchFileResult{}, nil } func (fs *eosfs) CreateReference(ctx context.Context, p string, targetURI *url.URL) error { @@ -1738,28 +1749,34 @@ func (fs *eosfs) CreateReference(ctx context.Context, p string, targetURI *url.U return nil } -func (fs *eosfs) Delete(ctx context.Context, ref *provider.Reference) error { +func (fs *eosfs) Delete(ctx context.Context, ref *provider.Reference) (*storage.DeleteResult, error) { p, err := fs.resolve(ctx, ref) if err != nil { - return errors.Wrap(err, "eosfs: error resolving reference") + return nil, errors.Wrap(err, "eosfs: error resolving reference") } if fs.isShareFolder(ctx, p) { - return fs.deleteShadow(ctx, p) + if err = fs.deleteShadow(ctx, p); err != nil { + return nil, err + } + return &storage.DeleteResult{}, nil } fn := fs.wrap(ctx, p) u, err := getUser(ctx) if err != nil { - return errors.Wrap(err, "eosfs: no user in ctx") + return nil, errors.Wrap(err, "eosfs: no user in ctx") } auth, err := fs.getUserAuth(ctx, u, fn) if err != nil { - return err + return nil, err } - return fs.c.Remove(ctx, auth, fn, false) + if err := fs.c.Remove(ctx, auth, fn, false); err != nil { + return nil, err + } + return &storage.DeleteResult{}, nil } func (fs *eosfs) deleteShadow(ctx context.Context, p string) error { @@ -1811,7 +1828,10 @@ func (fs *eosfs) Move(ctx context.Context, oldRef, newRef *provider.Reference) ( return nil, err } - return nil, fs.c.Rename(ctx, auth, oldFn, newFn) + if err := fs.c.Rename(ctx, auth, oldFn, newFn); err != nil { + return nil, err + } + return &storage.MoveResult{}, nil } func (fs *eosfs) moveShadow(ctx context.Context, oldPath, newPath string) error { @@ -1943,7 +1963,7 @@ func (fs *eosfs) DownloadRevision(ctx context.Context, ref *provider.Reference, return md, reader, err } -func (fs *eosfs) RestoreRevision(ctx context.Context, ref *provider.Reference, revisionKey string) error { +func (fs *eosfs) RestoreRevision(ctx context.Context, ref *provider.Reference, revisionKey string) (*storage.RestoreRevisionResult, error) { var auth eosclient.Authorization var fn string var err error @@ -1954,26 +1974,29 @@ func (fs *eosfs) RestoreRevision(ctx context.Context, ref *provider.Reference, r // if we have access to it. md, err := fs.GetMD(ctx, ref, nil, nil) if err != nil { - return err + return nil, err } fn = fs.wrap(ctx, md.Path) if md.PermissionSet.RestoreFileVersion { auth, err = fs.getUIDGateway(ctx, md.Owner) if err != nil { - return err + return nil, err } } else { - return errtypes.PermissionDenied("eosfs: user doesn't have permissions to restore revisions") + return nil, errtypes.PermissionDenied("eosfs: user doesn't have permissions to restore revisions") } } else { fn, auth, err = fs.resolveRefForbidShareFolder(ctx, ref) if err != nil { - return err + return nil, err } } - return fs.c.RollbackToVersion(ctx, auth, fn, revisionKey) + if err := fs.c.RollbackToVersion(ctx, auth, fn, revisionKey); err != nil { + return nil, err + } + return &storage.RestoreRevisionResult{}, nil } func (fs *eosfs) PurgeRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string) error { @@ -2044,7 +2067,7 @@ func (fs *eosfs) ListRecycle(ctx context.Context, ref *provider.Reference, key, return recycleEntries, nil } -func (fs *eosfs) RestoreRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string, restoreRef *provider.Reference) error { +func (fs *eosfs) RestoreRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string, restoreRef *provider.Reference) (*storage.RestoreRecycleItemResult, error) { var auth eosclient.Authorization if !fs.conf.EnableHome && fs.conf.AllowPathRecycleOperations && ref.Path != "/" { @@ -2053,29 +2076,32 @@ func (fs *eosfs) RestoreRecycleItem(ctx context.Context, ref *provider.Reference // if we have access to it. md, err := fs.GetMD(ctx, &provider.Reference{Path: ref.Path}, nil, nil) if err != nil { - return err + return nil, err } if md.PermissionSet.RestoreRecycleItem { auth, err = fs.getUIDGateway(ctx, md.Owner) if err != nil { - return err + return nil, err } } else { - return errtypes.PermissionDenied("eosfs: user doesn't have permissions to restore recycled items") + return nil, errtypes.PermissionDenied("eosfs: user doesn't have permissions to restore recycled items") } } else { // We just act on the logged-in user's recycle bin u, err := getUser(ctx) if err != nil { - return errors.Wrap(err, "eosfs: no user in ctx") + return nil, errors.Wrap(err, "eosfs: no user in ctx") } auth, err = fs.getUserAuth(ctx, u, "") if err != nil { - return err + return nil, err } } - return fs.c.RestoreDeletedEntry(ctx, auth, key) + if err := fs.c.RestoreDeletedEntry(ctx, auth, key); err != nil { + return nil, err + } + return &storage.RestoreRecycleItemResult{}, nil } func (fs *eosfs) convertToRecycleItem(ctx context.Context, eosDeletedItem *eosclient.DeletedEntry) (*provider.RecycleItem, error) { diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/eosfs/spaces.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/eosfs/spaces.go index 94a7e9a2ed..7856f324a7 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/eosfs/spaces.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/eosfs/spaces.go @@ -34,6 +34,7 @@ import ( "github.com/opencloud-eu/reva/v2/pkg/appctx" "github.com/opencloud-eu/reva/v2/pkg/eosclient" "github.com/opencloud-eu/reva/v2/pkg/errtypes" + "github.com/opencloud-eu/reva/v2/pkg/storage" "github.com/opencloud-eu/reva/v2/pkg/storage/utils/templates" "github.com/opencloud-eu/reva/v2/pkg/storagespace" "github.com/pkg/errors" @@ -360,6 +361,6 @@ func (fs *eosfs) UpdateStorageSpace(ctx context.Context, req *provider.UpdateSto return nil, errtypes.NotSupported("update storage space") } -func (fs *eosfs) DeleteStorageSpace(ctx context.Context, req *provider.DeleteStorageSpaceRequest) error { - return errtypes.NotSupported("delete storage spaces") +func (fs *eosfs) DeleteStorageSpace(ctx context.Context, req *provider.DeleteStorageSpaceRequest) (*storage.DeleteStorageSpaceResult, error) { + return nil, errtypes.NotSupported("delete storage spaces") } diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/eosfs/upload.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/eosfs/upload.go index 2645f151b5..99d17114c6 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/eosfs/upload.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/eosfs/upload.go @@ -20,85 +20,12 @@ package eosfs import ( "context" - "os" - "path" provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" "github.com/opencloud-eu/reva/v2/pkg/errtypes" "github.com/opencloud-eu/reva/v2/pkg/storage" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/chunking" - "github.com/pkg/errors" ) -func (fs *eosfs) Upload(ctx context.Context, req storage.UploadRequest, uff storage.UploadFinishedFunc) (*provider.ResourceInfo, error) { - p, err := fs.resolve(ctx, req.Ref) - if err != nil { - return &provider.ResourceInfo{}, errors.Wrap(err, "eos: error resolving reference") - } - - if fs.isShareFolder(ctx, p) { - return &provider.ResourceInfo{}, errtypes.PermissionDenied("eos: cannot upload under the virtual share folder") - } - - if chunking.IsChunked(p) { - var assembledFile string - p, assembledFile, err = fs.chunkHandler.WriteChunk(p, req.Body) - if err != nil { - return &provider.ResourceInfo{}, err - } - if p == "" { - return &provider.ResourceInfo{}, errtypes.PartialContent(req.Ref.String()) - } - fd, err := os.Open(assembledFile) - if err != nil { - return &provider.ResourceInfo{}, errors.Wrap(err, "eos: error opening assembled file") - } - defer fd.Close() - defer os.RemoveAll(assembledFile) - req.Body = fd - } - - fn := fs.wrap(ctx, p) - - u, err := getUser(ctx) - if err != nil { - return &provider.ResourceInfo{}, errors.Wrap(err, "eos: no user in ctx") - } - - // We need the auth corresponding to the parent directory - // as the file might not exist at the moment - auth, err := fs.getUserAuth(ctx, u, path.Dir(fn)) - if err != nil { - return &provider.ResourceInfo{}, err - } - - if err := fs.c.Write(ctx, auth, fn, req.Body); err != nil { - return &provider.ResourceInfo{}, err - } - - eosFileInfo, err := fs.c.GetFileInfoByPath(ctx, auth, fn) - if err != nil { - return &provider.ResourceInfo{}, err - } - - ri, err := fs.convertToResourceInfo(ctx, eosFileInfo) - if err != nil { - return &provider.ResourceInfo{}, err - } - - return ri, nil -} - -func (fs *eosfs) InitiateUpload(ctx context.Context, ref *provider.Reference, uploadLength int64, metadata map[string]string) (map[string]string, error) { - p, err := fs.resolve(ctx, ref) - if err != nil { - return nil, err - } - return map[string]string{ - "simple": p, - }, nil -} - func (fs *eosfs) MarkProcessing(ctx context.Context, ref *provider.Reference, processing bool, sessionID string) error { return errtypes.NotSupported("op not supported") } @@ -106,3 +33,11 @@ func (fs *eosfs) MarkProcessing(ctx context.Context, ref *provider.Reference, pr func (fs *eosfs) CommitUpload(_ context.Context, _ *provider.Reference, _ string, _ storage.UploadSource) error { return errtypes.NotSupported("op not supported") } + +func (fs *eosfs) PrepareUpload(_ context.Context, _ *provider.Reference, _ string, info storage.UploadInfo) (*storage.PrepareUploadResult, error) { + return &storage.PrepareUploadResult{VersionCreated: info.NodeExisted}, nil +} + +func (fs *eosfs) RollbackUpload(_ context.Context, _ *provider.Reference, _ string, _ storage.RollbackInfo) error { + return nil +} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/localfs/localfs.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/localfs/localfs.go index bcf918862c..e7cb458f5d 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/localfs/localfs.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/localfs/localfs.go @@ -731,8 +731,8 @@ func (fs *localfs) RemoveLabel(ctx context.Context, ref *provider.Reference, use } // SetLock puts a lock on the given reference -func (fs *localfs) SetLock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) error { - return errtypes.NotSupported("unimplemented") +func (fs *localfs) SetLock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) (*storage.SetLockResult, error) { + return nil, errtypes.NotSupported("unimplemented") } // RefreshLock refreshes an existing lock on the given reference @@ -741,8 +741,8 @@ func (fs *localfs) RefreshLock(ctx context.Context, ref *provider.Reference, loc } // Unlock removes an existing lock from the given reference -func (fs *localfs) Unlock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) error { - return errtypes.NotSupported("unimplemented") +func (fs *localfs) Unlock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) (*storage.UnlockResult, error) { + return nil, errtypes.NotSupported("unimplemented") } func (fs *localfs) GetHome(ctx context.Context) (string, error) { @@ -790,45 +790,48 @@ func (fs *localfs) createHomeInternal(ctx context.Context, fn string) error { return nil } -func (fs *localfs) CreateDir(ctx context.Context, ref *provider.Reference) error { +func (fs *localfs) CreateDir(ctx context.Context, ref *provider.Reference) (*storage.CreateDirResult, error) { fn, err := fs.resolve(ctx, ref) if err != nil { - return nil + return nil, err } if fs.isShareFolder(ctx, fn) { - return errtypes.PermissionDenied("localfs: cannot create folder under the share folder") + return nil, errtypes.PermissionDenied("localfs: cannot create folder under the share folder") } fn = fs.wrap(ctx, fn) if _, err := os.Stat(fn); err == nil { - return errtypes.AlreadyExists(fn) + return nil, errtypes.AlreadyExists(fn) } err = os.Mkdir(fn, 0700) if err != nil { if os.IsNotExist(err) { - return errtypes.PreconditionFailed(fn) + return nil, errtypes.PreconditionFailed(fn) } - return errors.Wrap(err, "localfs: error creating dir "+fn) + return nil, errors.Wrap(err, "localfs: error creating dir "+fn) } - return fs.propagate(ctx, path.Dir(fn)) + if err := fs.propagate(ctx, path.Dir(fn)); err != nil { + return nil, err + } + return &storage.CreateDirResult{}, nil } // TouchFile as defined in the storage.FS interface -func (fs *localfs) TouchFile(ctx context.Context, ref *provider.Reference, _ bool, _ string) error { - return fmt.Errorf("unimplemented: TouchFile") +func (fs *localfs) TouchFile(ctx context.Context, ref *provider.Reference, _ bool, _ string) (*storage.TouchFileResult, error) { + return nil, fmt.Errorf("unimplemented: TouchFile") } -func (fs *localfs) Delete(ctx context.Context, ref *provider.Reference) error { +func (fs *localfs) Delete(ctx context.Context, ref *provider.Reference) (*storage.DeleteResult, error) { fn, err := fs.resolve(ctx, ref) if err != nil { - return errors.Wrap(err, "localfs: error resolving ref") + return nil, errors.Wrap(err, "localfs: error resolving ref") } if fs.isShareFolderRoot(ctx, fn) { - return errtypes.PermissionDenied("localfs: cannot delete the virtual share folder") + return nil, errtypes.PermissionDenied("localfs: cannot delete the virtual share folder") } var fp string @@ -841,22 +844,25 @@ func (fs *localfs) Delete(ctx context.Context, ref *provider.Reference) error { _, err = os.Stat(fp) if err != nil { if os.IsNotExist(err) { - return errtypes.NotFound(fn) + return nil, errtypes.NotFound(fn) } - return errors.Wrap(err, "localfs: error stating "+fp) + return nil, errors.Wrap(err, "localfs: error stating "+fp) } key := fmt.Sprintf("%s.d%d", path.Base(fn), time.Now().UnixNano()/int64(time.Millisecond)) if err := os.Rename(fp, fs.wrapRecycleBin(ctx, key)); err != nil { - return errors.Wrap(err, "localfs: could not delete item") + return nil, errors.Wrap(err, "localfs: could not delete item") } err = fs.addToRecycledDB(ctx, key, fn) if err != nil { - return errors.Wrap(err, "localfs: error adding entry to DB") + return nil, errors.Wrap(err, "localfs: error adding entry to DB") } - return fs.propagate(ctx, path.Dir(fp)) + if err := fs.propagate(ctx, path.Dir(fp)); err != nil { + return nil, err + } + return &storage.DeleteResult{}, nil } func (fs *localfs) Move(ctx context.Context, oldRef, newRef *provider.Reference) (*storage.MoveResult, error) { @@ -892,7 +898,7 @@ func (fs *localfs) Move(ctx context.Context, oldRef, newRef *provider.Reference) return nil, err } - return nil, nil + return &storage.MoveResult{}, nil } func (fs *localfs) moveReferences(ctx context.Context, oldName, newName string) error { @@ -1183,14 +1189,14 @@ func (fs *localfs) DownloadRevision(ctx context.Context, ref *provider.Reference return ri, r, nil } -func (fs *localfs) RestoreRevision(ctx context.Context, ref *provider.Reference, revisionKey string) error { +func (fs *localfs) RestoreRevision(ctx context.Context, ref *provider.Reference, revisionKey string) (*storage.RestoreRevisionResult, error) { np, err := fs.resolve(ctx, ref) if err != nil { - return errors.Wrap(err, "localfs: error resolving ref") + return nil, errors.Wrap(err, "localfs: error resolving ref") } if fs.isShareFolder(ctx, np) { - return errtypes.PermissionDenied("localfs: cannot restore revisions under the virtual share folder") + return nil, errtypes.PermissionDenied("localfs: cannot restore revisions under the virtual share folder") } versionsDir := fs.wrapVersions(ctx, np) @@ -1201,24 +1207,27 @@ func (fs *localfs) RestoreRevision(ctx context.Context, ref *provider.Reference, vs, err := os.Stat(vp) if err != nil { if os.IsNotExist(err) { - return errtypes.NotFound(revisionKey) + return nil, errtypes.NotFound(revisionKey) } - return errors.Wrap(err, "localfs: error stating "+vp) + return nil, errors.Wrap(err, "localfs: error stating "+vp) } if !vs.Mode().IsRegular() { - return fmt.Errorf("%s is not a regular file", vp) + return nil, fmt.Errorf("%s is not a regular file", vp) } if err := fs.archiveRevision(ctx, np); err != nil { - return err + return nil, err } if err := os.Rename(vp, np); err != nil { - return errors.Wrap(err, "localfs: error renaming from "+vp+" to "+np) + return nil, errors.Wrap(err, "localfs: error renaming from "+vp+" to "+np) } - return fs.propagate(ctx, np) + if err := fs.propagate(ctx, np); err != nil { + return nil, err + } + return &storage.RestoreRevisionResult{}, nil } func (fs *localfs) PurgeRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string) error { @@ -1290,16 +1299,16 @@ func (fs *localfs) ListRecycle(ctx context.Context, ref *provider.Reference, key return items, nil } -func (fs *localfs) RestoreRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string, restoreRef *provider.Reference) error { +func (fs *localfs) RestoreRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string, restoreRef *provider.Reference) (*storage.RestoreRecycleItemResult, error) { suffix := path.Ext(key) if len(suffix) == 0 || !strings.HasPrefix(suffix, ".d") { - return errors.New("localfs: invalid trash item suffix") + return nil, errors.New("localfs: invalid trash item suffix") } filePath, err := fs.getRecycledEntry(ctx, key) if err != nil { - return errors.Wrap(err, "localfs: invalid key") + return nil, errors.Wrap(err, "localfs: invalid key") } var localRestorePath string @@ -1313,27 +1322,30 @@ func (fs *localfs) RestoreRecycleItem(ctx context.Context, ref *provider.Referen } if _, err = os.Stat(localRestorePath); err == nil { - return errors.New("localfs: can't restore - file already exists at original path") + return nil, errors.New("localfs: can't restore - file already exists at original path") } rp := fs.wrapRecycleBin(ctx, key) if _, err = os.Stat(rp); err != nil { if os.IsNotExist(err) { - return errtypes.NotFound(key) + return nil, errtypes.NotFound(key) } - return errors.Wrap(err, "localfs: error stating "+rp) + return nil, errors.Wrap(err, "localfs: error stating "+rp) } if err := os.Rename(rp, localRestorePath); err != nil { - return errors.Wrap(err, "ocfs: could not restore item") + return nil, errors.Wrap(err, "ocfs: could not restore item") } err = fs.removeFromRecycledDB(ctx, key) if err != nil { - return errors.Wrap(err, "localfs: error adding entry to DB") + return nil, errors.Wrap(err, "localfs: error adding entry to DB") } - return fs.propagate(ctx, localRestorePath) + if err := fs.propagate(ctx, localRestorePath); err != nil { + return nil, err + } + return &storage.RestoreRecycleItemResult{}, nil } func (fs *localfs) ListStorageSpaces(ctx context.Context, filter []*provider.ListStorageSpacesRequest_Filter, unrestricted bool) ([]*provider.StorageSpace, error) { @@ -1346,8 +1358,8 @@ func (fs *localfs) UpdateStorageSpace(ctx context.Context, req *provider.UpdateS } // DeleteStorageSpace deletes a storage space -func (fs *localfs) DeleteStorageSpace(ctx context.Context, req *provider.DeleteStorageSpaceRequest) error { - return errtypes.NotSupported("delete storage space") +func (fs *localfs) DeleteStorageSpace(ctx context.Context, req *provider.DeleteStorageSpaceRequest) (*storage.DeleteStorageSpaceResult, error) { + return nil, errtypes.NotSupported("delete storage space") } func (fs *localfs) propagate(ctx context.Context, leafPath string) error { diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/localfs/upload.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/localfs/upload.go index 3ae7962824..c901ef5003 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/localfs/upload.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/localfs/upload.go @@ -20,137 +20,12 @@ package localfs import ( "context" - "encoding/json" - "io" - "os" - "path/filepath" - userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" - "github.com/google/uuid" - "github.com/opencloud-eu/reva/v2/pkg/appctx" - ctxpkg "github.com/opencloud-eu/reva/v2/pkg/ctx" "github.com/opencloud-eu/reva/v2/pkg/errtypes" "github.com/opencloud-eu/reva/v2/pkg/storage" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/chunking" - "github.com/opencloud-eu/reva/v2/pkg/utils" - "github.com/pkg/errors" - tusd "github.com/tus/tusd/v2/pkg/handler" ) -var defaultFilePerm = os.FileMode(0664) - -func (fs *localfs) Upload(ctx context.Context, req storage.UploadRequest, uff storage.UploadFinishedFunc) (*provider.ResourceInfo, error) { - upload, err := fs.GetUpload(ctx, req.Ref.GetPath()) - if err != nil { - return &provider.ResourceInfo{}, errors.Wrap(err, "localfs: error retrieving upload") - } - - uploadInfo := upload.(*fileUpload) - - p := uploadInfo.info.Storage["InternalDestination"] - if chunking.IsChunked(p) { - var assembledFile string - p, assembledFile, err = fs.chunkHandler.WriteChunk(p, req.Body) - if err != nil { - return &provider.ResourceInfo{}, err - } - if p == "" { - if err = uploadInfo.Terminate(ctx); err != nil { - return &provider.ResourceInfo{}, errors.Wrap(err, "localfs: error removing auxiliary files") - } - return &provider.ResourceInfo{}, errtypes.PartialContent(req.Ref.String()) - } - uploadInfo.info.Storage["InternalDestination"] = p - fd, err := os.Open(assembledFile) - if err != nil { - return &provider.ResourceInfo{}, errors.Wrap(err, "localfs: error opening assembled file") - } - defer fd.Close() - defer os.RemoveAll(assembledFile) - req.Body = fd - } - - if _, err := uploadInfo.WriteChunk(ctx, 0, req.Body); err != nil { - return &provider.ResourceInfo{}, errors.Wrap(err, "localfs: error writing to binary file") - } - - if err := uploadInfo.FinishUpload(ctx); err != nil { - return &provider.ResourceInfo{}, err - } - - if uff != nil { - info := uploadInfo.info - uploadRef := &provider.Reference{ - ResourceId: &provider.ResourceId{ - StorageId: info.MetaData["providerID"], - SpaceId: info.Storage["SpaceRoot"], - OpaqueId: info.Storage["SpaceRoot"], - }, - Path: utils.MakeRelativePath(filepath.Join(info.MetaData["dir"], info.MetaData["filename"])), - } - owner, ok := ctxpkg.ContextGetUser(uploadInfo.ctx) - if !ok { - return &provider.ResourceInfo{}, errtypes.PreconditionFailed("error getting user from uploadinfo context") - } - // spaces support in localfs needs to be revisited: - // * info.Storage["SpaceRoot"] is never set - // * there is no space owner or manager that could be passed to the UploadFinishedFunc - uff(owner.Id, owner.Id, uploadRef) - } - - // return id, etag and mtime - ri, err := fs.GetMD(ctx, req.Ref, []string{}, []string{"id", "etag", "mtime"}) - if err != nil { - return &provider.ResourceInfo{}, err - } - - return ri, nil -} - -// InitiateUpload returns upload ids corresponding to different protocols it supports -// It resolves the resource and then reuses the NewUpload function -// Currently requires the uploadLength to be set -// TODO to implement LengthDeferrerDataStore make size optional -// TODO read optional content for small files in this request -func (fs *localfs) InitiateUpload(ctx context.Context, ref *provider.Reference, uploadLength int64, metadata map[string]string) (map[string]string, error) { - - np, err := fs.resolve(ctx, ref) - if err != nil { - return nil, errors.Wrap(err, "localfs: error resolving reference") - } - - info := tusd.FileInfo{ - MetaData: tusd.MetaData{ - "filename": filepath.Base(np), - "dir": filepath.Dir(np), - }, - Size: uploadLength, - } - - if metadata != nil { - info.MetaData["providerID"] = metadata["providerID"] - if metadata["mtime"] != "" { - info.MetaData["mtime"] = metadata["mtime"] - } - if _, ok := metadata["sizedeferred"]; ok { - info.SizeIsDeferred = true - } - } - - upload, err := fs.NewUpload(ctx, info) - if err != nil { - return nil, err - } - - info, _ = upload.GetInfo(ctx) - - return map[string]string{ - "simple": info.ID, - "tus": info.ID, - }, nil -} - func (fs *localfs) MarkProcessing(ctx context.Context, ref *provider.Reference, processing bool, sessionID string) error { return errtypes.NotSupported("op not supported") } @@ -159,246 +34,10 @@ func (fs *localfs) CommitUpload(_ context.Context, _ *provider.Reference, _ stri return errtypes.NotSupported("op not supported") } -// UseIn tells the tus upload middleware which extensions it supports. -func (fs *localfs) UseIn(composer *tusd.StoreComposer) { - composer.UseCore(fs) - composer.UseTerminater(fs) - // TODO composer.UseConcater(fs) - // TODO composer.UseLengthDeferrer(fs) +func (fs *localfs) PrepareUpload(_ context.Context, _ *provider.Reference, _ string, info storage.UploadInfo) (*storage.PrepareUploadResult, error) { + return &storage.PrepareUploadResult{VersionCreated: info.NodeExisted}, nil } -// NewUpload creates a new upload using the size as the file's length. To determine where to write the binary data -// the Fileinfo metadata must contain a dir and a filename. -// returns a unique id which is used to identify the upload. The properties Size and MetaData will be filled. -func (fs *localfs) NewUpload(ctx context.Context, info tusd.FileInfo) (upload tusd.Upload, err error) { - - log := appctx.GetLogger(ctx) - log.Debug().Interface("info", info).Msg("localfs: NewUpload") - - fn := info.MetaData["filename"] - if fn == "" { - return nil, errors.New("localfs: missing filename in metadata") - } - info.MetaData["filename"] = filepath.Clean(info.MetaData["filename"]) - - dir := info.MetaData["dir"] - if dir == "" { - return nil, errors.New("localfs: missing dir in metadata") - } - info.MetaData["dir"] = filepath.Clean(info.MetaData["dir"]) - - np := fs.wrap(ctx, filepath.Join(info.MetaData["dir"], info.MetaData["filename"])) - - log.Debug().Interface("info", info).Msg("localfs: resolved filename") - - info.ID = uuid.New().String() - - binPath, err := fs.getUploadPath(ctx, info.ID) - if err != nil { - return nil, errors.Wrap(err, "localfs: error resolving upload path") - } - usr := ctxpkg.ContextMustGetUser(ctx) - info.Storage = map[string]string{ - "Type": "LocalStore", - "BinPath": binPath, - "InternalDestination": np, - - "Idp": usr.Id.Idp, - "UserId": usr.Id.OpaqueId, - "UserName": usr.Username, - "UserType": utils.UserTypeToString(usr.Id.Type), - - "LogLevel": log.GetLevel().String(), - } - // Create binary file with no content - file, err := os.OpenFile(binPath, os.O_CREATE|os.O_WRONLY, defaultFilePerm) - if err != nil { - return nil, err - } - defer file.Close() - - u := &fileUpload{ - info: info, - binPath: binPath, - infoPath: binPath + ".info", - fs: fs, - ctx: ctx, - } - - // writeInfo creates the file by itself if necessary - err = u.writeInfo() - if err != nil { - return nil, err - } - - return u, nil -} - -func (fs *localfs) getUploadPath(ctx context.Context, uploadID string) (string, error) { - return filepath.Join(fs.conf.Uploads, uploadID), nil -} - -// GetUpload returns the Upload for the given upload id -func (fs *localfs) GetUpload(ctx context.Context, id string) (tusd.Upload, error) { - binPath, err := fs.getUploadPath(ctx, id) - if err != nil { - return nil, err - } - infoPath := binPath + ".info" - info := tusd.FileInfo{} - data, err := os.ReadFile(infoPath) - if err != nil { - if os.IsNotExist(err) { - // Interpret os.ErrNotExist as 404 Not Found - err = tusd.ErrNotFound - } - return nil, err - } - if err := json.Unmarshal(data, &info); err != nil { - return nil, err - } - - stat, err := os.Stat(binPath) - if err != nil { - return nil, err - } - - info.Offset = stat.Size() - - u := &userpb.User{ - Id: &userpb.UserId{ - Idp: info.Storage["Idp"], - OpaqueId: info.Storage["UserId"], - Type: utils.UserTypeMap(info.Storage["UserType"]), - }, - Username: info.Storage["UserName"], - } - - ctx = ctxpkg.ContextSetUser(ctx, u) - - return &fileUpload{ - info: info, - binPath: binPath, - infoPath: infoPath, - fs: fs, - ctx: ctx, - }, nil -} - -type fileUpload struct { - // info stores the current information about the upload - info tusd.FileInfo - // infoPath is the path to the .info file - infoPath string - // binPath is the path to the binary file (which has no extension) - binPath string - // only fs knows how to handle metadata and versions - fs *localfs - // a context with a user - ctx context.Context -} - -// GetInfo returns the FileInfo -func (upload *fileUpload) GetInfo(ctx context.Context) (tusd.FileInfo, error) { - return upload.info, nil -} - -// GetReader returns an io.Reader for the upload -func (upload *fileUpload) GetReader(ctx context.Context) (io.ReadCloser, error) { - return os.Open(upload.binPath) -} - -// WriteChunk writes the stream from the reader to the given offset of the upload -func (upload *fileUpload) WriteChunk(ctx context.Context, offset int64, src io.Reader) (int64, error) { - file, err := os.OpenFile(upload.binPath, os.O_WRONLY|os.O_APPEND, defaultFilePerm) - if err != nil { - return 0, err - } - defer file.Close() - - n, err := io.Copy(file, src) - - // If the HTTP PATCH request gets interrupted in the middle (e.g. because - // the user wants to pause the upload), Go's net/http returns an io.ErrUnexpectedEOF. - // However, for the driver it's not important whether the stream has ended - // on purpose or accidentally. - if err != nil { - if err != io.ErrUnexpectedEOF { - return n, err - } - } - - upload.info.Offset += n - err = upload.writeInfo() - - return n, err -} - -// writeInfo updates the entire information. Everything will be overwritten. -func (upload *fileUpload) writeInfo() error { - data, err := json.Marshal(upload.info) - if err != nil { - return err - } - return os.WriteFile(upload.infoPath, data, defaultFilePerm) -} - -// FinishUpload finishes an upload and moves the file to the internal destination -func (upload *fileUpload) FinishUpload(ctx context.Context) error { - - np := upload.info.Storage["InternalDestination"] - - // TODO check etag with If-Match header - // if destination exists - // if _, err := os.Stat(np); err == nil { - // the local storage does not store metadata - // the fileid is based on the path, so no we do not need to copy it to the new file - // the local storage does not track revisions - //} - - // if destination exists - if _, err := os.Stat(np); err == nil { - // create revision - if err := upload.fs.archiveRevision(upload.ctx, np); err != nil { - return err - } - } - - err := os.Rename(upload.binPath, np) - if err != nil { - return err - } - - // only delete the upload if it was successfully written to the fs - if err := os.Remove(upload.infoPath); err != nil { - if !os.IsNotExist(err) { - log := appctx.GetLogger(ctx) - log.Err(err).Interface("info", upload.info).Msg("localfs: could not delete upload info") - } - } - - // TODO: set mtime if specified in metadata - - // metadata propagation is left to the storage implementation - return err -} - -// To implement the termination extension as specified in https://tus.io/protocols/resumable-upload.html#termination -// - the storage needs to implement AsTerminatableUpload -// - the upload needs to implement Terminate - -// AsTerminatableUpload returns a a TerminatableUpload -func (fs *localfs) AsTerminatableUpload(upload tusd.Upload) tusd.TerminatableUpload { - return upload.(*fileUpload) -} - -// Terminate terminates the upload -func (upload *fileUpload) Terminate(ctx context.Context) error { - if err := os.Remove(upload.infoPath); err != nil { - return err - } - if err := os.Remove(upload.binPath); err != nil { - return err - } +func (fs *localfs) RollbackUpload(_ context.Context, _ *provider.Reference, _ string, _ storage.RollbackInfo) error { return nil } diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/middleware/middleware.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/middleware/middleware.go index 94ec157be2..3ba3745e1a 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/middleware/middleware.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/middleware/middleware.go @@ -25,9 +25,7 @@ import ( userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" - tusd "github.com/tus/tusd/v2/pkg/handler" - "github.com/opencloud-eu/reva/v2/pkg/errtypes" "github.com/opencloud-eu/reva/v2/pkg/storage" "github.com/opencloud-eu/reva/v2/pkg/storagespace" ) @@ -58,58 +56,17 @@ func (fs *FS) WithDisabledSpaces() storage.FS { return &f } -// ListUploadSessions returns the upload sessions matching the given filter -func (f *FS) ListUploadSessions(ctx context.Context, filter storage.UploadSessionFilter) ([]storage.UploadSession, error) { - return f.next.(storage.UploadSessionLister).ListUploadSessions(ctx, filter) +// IsOrphaned reports whether the referenced resource exists but its metadata is unreadable. +func (f *FS) IsOrphaned(ctx context.Context, ref *provider.Reference) bool { + return f.next.(storage.OrphanChecker).IsOrphaned(ctx, ref) } -// ResolveUpload resolves a finished upload to the resource it produced, read as the upload's -// executant. It is best effort: if the wrapped storage does not resolve uploads it returns -// NotSupported rather than panicking, so the tus finalize falls back to no headers. -func (f *FS) ResolveUpload(ctx context.Context, info tusd.FileInfo) (*provider.ResourceInfo, context.Context, error) { - r, ok := f.next.(storage.UploadSessionResolver) - if !ok { - return nil, ctx, errtypes.NotSupported("storage does not resolve upload sessions") - } - return r.ResolveUpload(ctx, info) +// PrepareCreatesNode reports whether the wrapped driver's PrepareUpload creates a +// new file's node. +func (f *FS) PrepareCreatesNode() bool { + nc, ok := f.next.(storage.NodeCreator) + return ok && nc.PrepareCreatesNode() } - -// UseIn tells the tus upload middleware which extensions it supports. -func (f *FS) UseIn(composer *tusd.StoreComposer) { - f.next.(storage.ComposableFS).UseIn(composer) -} - -// NewUpload returns a new tus Upload instance -func (f *FS) NewUpload(ctx context.Context, info tusd.FileInfo) (upload tusd.Upload, err error) { - return f.next.(tusd.DataStore).NewUpload(ctx, info) -} - -// NewUpload returns a new tus Upload instance -func (f *FS) GetUpload(ctx context.Context, id string) (upload tusd.Upload, err error) { - return f.next.(tusd.DataStore).GetUpload(ctx, id) -} - -// AsTerminatableUpload returns a TerminatableUpload -// To implement the termination extension as specified in https://tus.io/protocols/resumable-upload.html#termination -// the storage needs to implement AsTerminatableUpload -func (f *FS) AsTerminatableUpload(up tusd.Upload) tusd.TerminatableUpload { - return f.next.(tusd.TerminaterDataStore).AsTerminatableUpload(up) -} - -// AsLengthDeclarableUpload returns a LengthDeclarableUpload -// To implement the creation-defer-length extension as specified in https://tus.io/protocols/resumable-upload.html#creation -// the storage needs to implement AsLengthDeclarableUpload -func (f *FS) AsLengthDeclarableUpload(up tusd.Upload) tusd.LengthDeclarableUpload { - return f.next.(tusd.LengthDeferrerDataStore).AsLengthDeclarableUpload(up) -} - -// AsConcatableUpload returns a ConcatableUpload -// To implement the concatenation extension as specified in https://tus.io/protocols/resumable-upload.html#concatenation -// the storage needs to implement AsConcatableUpload -func (f *FS) AsConcatableUpload(up tusd.Upload) tusd.ConcatableUpload { - return f.next.(tusd.ConcaterDataStore).AsConcatableUpload(up) -} - func (f *FS) GetHome(ctx context.Context) (string, error) { var ( err error @@ -164,7 +121,7 @@ func (f *FS) CreateHome(ctx context.Context) error { return res0 } -func (f *FS) CreateDir(ctx context.Context, ref *provider.Reference) error { +func (f *FS) CreateDir(ctx context.Context, ref *provider.Reference) (*storage.CreateDirResult, error) { var ( err error unhook UnHook @@ -173,25 +130,25 @@ func (f *FS) CreateDir(ctx context.Context, ref *provider.Reference) error { for _, hook := range f.hooks { ctx, unhook, err = hook("CreateDir", ctx, ref.GetResourceId().GetSpaceId()) if err != nil { - return err + return nil, err } if unhook != nil { unhooks = append(unhooks, unhook) } } - res0 := f.next.CreateDir(ctx, ref) + result, err := f.next.CreateDir(ctx, ref) for _, unhook := range unhooks { if err := unhook(); err != nil { - return err + return nil, err } } - return res0 + return result, err } -func (f *FS) TouchFile(ctx context.Context, ref *provider.Reference, markprocessing bool, mtime string) error { +func (f *FS) TouchFile(ctx context.Context, ref *provider.Reference, markprocessing bool, mtime string) (*storage.TouchFileResult, error) { var ( err error unhook UnHook @@ -200,25 +157,25 @@ func (f *FS) TouchFile(ctx context.Context, ref *provider.Reference, markprocess for _, hook := range f.hooks { ctx, unhook, err = hook("TouchFile", ctx, ref.GetResourceId().GetSpaceId()) if err != nil { - return err + return nil, err } if unhook != nil { unhooks = append(unhooks, unhook) } } - res0 := f.next.TouchFile(ctx, ref, markprocessing, mtime) + result, err := f.next.TouchFile(ctx, ref, markprocessing, mtime) for _, unhook := range unhooks { if err := unhook(); err != nil { - return err + return nil, err } } - return res0 + return result, err } -func (f *FS) Delete(ctx context.Context, ref *provider.Reference) error { +func (f *FS) Delete(ctx context.Context, ref *provider.Reference) (*storage.DeleteResult, error) { var ( err error unhook UnHook @@ -227,22 +184,22 @@ func (f *FS) Delete(ctx context.Context, ref *provider.Reference) error { for _, hook := range f.hooks { ctx, unhook, err = hook("Delete", ctx, ref.GetResourceId().GetSpaceId()) if err != nil { - return err + return nil, err } if unhook != nil { unhooks = append(unhooks, unhook) } } - res0 := f.next.Delete(ctx, ref) + res0, err := f.next.Delete(ctx, ref) for _, unhook := range unhooks { if err := unhook(); err != nil { - return err + return nil, err } } - return res0 + return res0, err } func (f *FS) Move(ctx context.Context, oldRef, newRef *provider.Reference) (*storage.MoveResult, error) { @@ -326,60 +283,6 @@ func (f *FS) ListFolder(ctx context.Context, ref *provider.Reference, mdKeys, fi return res0, res1 } -func (f *FS) InitiateUpload(ctx context.Context, ref *provider.Reference, uploadLength int64, metadata map[string]string) (map[string]string, error) { - var ( - err error - unhook UnHook - unhooks []UnHook - ) - for _, hook := range f.hooks { - ctx, unhook, err = hook("InitiateUpload", ctx, ref.GetResourceId().GetSpaceId()) - if err != nil { - return nil, err - } - if unhook != nil { - unhooks = append(unhooks, unhook) - } - } - - res0, res1 := f.next.InitiateUpload(ctx, ref, uploadLength, metadata) - - for _, unhook := range unhooks { - if err := unhook(); err != nil { - return nil, err - } - } - - return res0, res1 -} - -func (f *FS) Upload(ctx context.Context, req storage.UploadRequest, uploadFunc storage.UploadFinishedFunc) (*provider.ResourceInfo, error) { - var ( - err error - unhook UnHook - unhooks []UnHook - ) - for _, hook := range f.hooks { - ctx, unhook, err = hook("Upload", ctx, req.Ref.GetResourceId().GetSpaceId()) - if err != nil { - return &provider.ResourceInfo{}, err - } - if unhook != nil { - unhooks = append(unhooks, unhook) - } - } - - res0, res1 := f.next.Upload(ctx, req, uploadFunc) - - for _, unhook := range unhooks { - if err := unhook(); err != nil { - return &provider.ResourceInfo{}, err - } - } - - return res0, res1 -} - func (f *FS) MarkProcessing(ctx context.Context, ref *provider.Reference, processing bool, sessionID string) error { var ( err error @@ -434,6 +337,37 @@ func (f *FS) CommitUpload(ctx context.Context, ref *provider.Reference, sessionI return err } +func (f *FS) PrepareUpload(ctx context.Context, ref *provider.Reference, sessionID string, info storage.UploadInfo) (*storage.PrepareUploadResult, error) { + var ( + err error + unhook UnHook + unhooks []UnHook + ) + for _, hook := range f.hooks { + ctx, unhook, err = hook("PrepareUpload", ctx, ref.GetResourceId().GetSpaceId()) + if err != nil { + return nil, err + } + if unhook != nil { + unhooks = append(unhooks, unhook) + } + } + + res, err := f.next.PrepareUpload(ctx, ref, sessionID, info) + + for _, unhook := range unhooks { + if uerr := unhook(); uerr != nil { + return nil, uerr + } + } + + return res, err +} + +func (f *FS) RollbackUpload(ctx context.Context, ref *provider.Reference, sessionID string, info storage.RollbackInfo) error { + return f.next.RollbackUpload(ctx, ref, sessionID, info) +} + func (f *FS) Download(ctx context.Context, ref *provider.Reference, openReaderFunc func(md *provider.ResourceInfo) bool) (*provider.ResourceInfo, io.ReadCloser, error) { var ( err error @@ -515,7 +449,7 @@ func (f *FS) DownloadRevision(ctx context.Context, ref *provider.Reference, key return res0, res1, res2 } -func (f *FS) RestoreRevision(ctx context.Context, ref *provider.Reference, key string) error { +func (f *FS) RestoreRevision(ctx context.Context, ref *provider.Reference, key string) (*storage.RestoreRevisionResult, error) { var ( err error unhook UnHook @@ -524,22 +458,22 @@ func (f *FS) RestoreRevision(ctx context.Context, ref *provider.Reference, key s for _, hook := range f.hooks { ctx, unhook, err = hook("RestoreRevision", ctx, ref.GetResourceId().GetSpaceId()) if err != nil { - return err + return nil, err } if unhook != nil { unhooks = append(unhooks, unhook) } } - res0 := f.next.RestoreRevision(ctx, ref, key) + result, err := f.next.RestoreRevision(ctx, ref, key) for _, unhook := range unhooks { if err := unhook(); err != nil { - return err + return nil, err } } - return res0 + return result, err } func (f *FS) ListRecycle(ctx context.Context, ref *provider.Reference, key, relativePath string) ([]*provider.RecycleItem, error) { @@ -569,7 +503,7 @@ func (f *FS) ListRecycle(ctx context.Context, ref *provider.Reference, key, rela return res0, res1 } -func (f *FS) RestoreRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string, restoreRef *provider.Reference) error { +func (f *FS) RestoreRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string, restoreRef *provider.Reference) (*storage.RestoreRecycleItemResult, error) { var ( err error unhook UnHook @@ -578,22 +512,22 @@ func (f *FS) RestoreRecycleItem(ctx context.Context, ref *provider.Reference, ke for _, hook := range f.hooks { ctx, unhook, err = hook("RestoreRecycleItem", ctx, ref.GetResourceId().GetSpaceId()) if err != nil { - return err + return nil, err } if unhook != nil { unhooks = append(unhooks, unhook) } } - res0 := f.next.RestoreRecycleItem(ctx, ref, key, relativePath, restoreRef) + result, err := f.next.RestoreRecycleItem(ctx, ref, key, relativePath, restoreRef) for _, unhook := range unhooks { if err := unhook(); err != nil { - return err + return nil, err } } - return res0 + return result, err } func (f *FS) PurgeRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string) error { @@ -943,7 +877,7 @@ func (f *FS) UnsetArbitraryMetadata(ctx context.Context, ref *provider.Reference return res0 } -func (f *FS) SetLock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) error { +func (f *FS) SetLock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) (*storage.SetLockResult, error) { var ( err error unhook UnHook @@ -952,22 +886,22 @@ func (f *FS) SetLock(ctx context.Context, ref *provider.Reference, lock *provide for _, hook := range f.hooks { ctx, unhook, err = hook("SetLock", ctx, ref.GetResourceId().GetSpaceId()) if err != nil { - return err + return nil, err } if unhook != nil { unhooks = append(unhooks, unhook) } } - res0 := f.next.SetLock(ctx, ref, lock) + result, err := f.next.SetLock(ctx, ref, lock) for _, unhook := range unhooks { if err := unhook(); err != nil { - return err + return nil, err } } - return res0 + return result, err } func (f *FS) GetLock(ctx context.Context, ref *provider.Reference) (*provider.Lock, error) { @@ -1024,7 +958,7 @@ func (f *FS) RefreshLock(ctx context.Context, ref *provider.Reference, lock *pro return res0 } -func (f *FS) Unlock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) error { +func (f *FS) Unlock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) (*storage.UnlockResult, error) { var ( err error unhook UnHook @@ -1033,22 +967,22 @@ func (f *FS) Unlock(ctx context.Context, ref *provider.Reference, lock *provider for _, hook := range f.hooks { ctx, unhook, err = hook("Unlock", ctx, ref.GetResourceId().GetSpaceId()) if err != nil { - return err + return nil, err } if unhook != nil { unhooks = append(unhooks, unhook) } } - res0 := f.next.Unlock(ctx, ref, lock) + result, err := f.next.Unlock(ctx, ref, lock) for _, unhook := range unhooks { if err := unhook(); err != nil { - return err + return nil, err } } - return res0 + return result, err } func (f *FS) ListStorageSpaces(ctx context.Context, filter []*provider.ListStorageSpacesRequest_Filter, unrestricted bool) ([]*provider.StorageSpace, error) { @@ -1135,7 +1069,7 @@ func (f *FS) UpdateStorageSpace(ctx context.Context, req *provider.UpdateStorage return res0, res1 } -func (f *FS) DeleteStorageSpace(ctx context.Context, req *provider.DeleteStorageSpaceRequest) error { +func (f *FS) DeleteStorageSpace(ctx context.Context, req *provider.DeleteStorageSpaceRequest) (*storage.DeleteStorageSpaceResult, error) { var ( err error unhook UnHook @@ -1144,22 +1078,22 @@ func (f *FS) DeleteStorageSpace(ctx context.Context, req *provider.DeleteStorage for _, hook := range f.hooks { ctx, unhook, err = hook("DeleteStorageSpace", ctx, req.GetId().GetOpaqueId()) if err != nil { - return err + return nil, err } if unhook != nil { unhooks = append(unhooks, unhook) } } - res0 := f.next.DeleteStorageSpace(ctx, req) + res0, err := f.next.DeleteStorageSpace(ctx, req) for _, unhook := range unhooks { if err := unhook(); err != nil { - return err + return nil, err } } - return res0 + return res0, err } func (f *FS) AddLabel(ctx context.Context, ref *provider.Reference, userID *userpb.UserId, label string) error { diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storagespace/context.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storagespace/context.go index 290f106092..0e65c7e416 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storagespace/context.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/storagespace/context.go @@ -22,46 +22,151 @@ import ( "context" userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" - "github.com/opencloud-eu/reva/v2/pkg/storage" ) type key int const ( - sendOwnerChanKey key = iota + spaceOwnerSlotKey key = iota moveResultSlotKey + deleteResultSlotKey + deleteStorageSpaceResultSlotKey ) -// ContextSendSpaceOwnerID stores the space owner in the context. -func ContextSendSpaceOwnerID(ctx context.Context, id *userpb.UserId) { - ch, ok := ctx.Value(sendOwnerChanKey).(chan<- *userpb.UserId) - if ok { - go func() { - ch <- id - close(ch) - }() +// --- space owner --- + +type spaceOwnerSlot struct { + ownerID *userpb.UserId +} + +// ContextRegisterSpaceOwnerSlot installs an empty slot in ctx so that the +// storage driver can write the space owner via ContextSetSpaceOwner and the +// events middleware can read it via ContextGetSpaceOwner after the handler +// returns. Subsequent registrations are no-ops; the first registration wins. +func ContextRegisterSpaceOwnerSlot(ctx context.Context) context.Context { + if ctx.Value(spaceOwnerSlotKey) != nil { + return ctx + } + return context.WithValue(ctx, spaceOwnerSlotKey, &spaceOwnerSlot{}) +} + +// ContextSetSpaceOwner writes id into the slot. Subsequent writes overwrite +// the previous value. Does nothing if no slot was registered. +func ContextSetSpaceOwner(ctx context.Context, id *userpb.UserId) { + if slot, ok := ctx.Value(spaceOwnerSlotKey).(*spaceOwnerSlot); ok { + slot.ownerID = id } } -// ContextRegisterSendOwnerChan registers a channel to send the current space owner -func ContextRegisterSendOwnerChan(ctx context.Context, ch chan<- *userpb.UserId) context.Context { - return context.WithValue(ctx, sendOwnerChanKey, ch) +// ContextGetSpaceOwner returns the space owner written by the storage driver, +// or nil if none was set. +func ContextGetSpaceOwner(ctx context.Context) *userpb.UserId { + if slot, ok := ctx.Value(spaceOwnerSlotKey).(*spaceOwnerSlot); ok { + return slot.ownerID + } + return nil } -// MoveResultSlot is a mutable container for a *storage.MoveResult. -type MoveResultSlot struct { - Result *storage.MoveResult +// --- move result --- + +type moveResultSlot struct { + result *storage.MoveResult } -// ContextRegisterMoveResultSlot stores an empty slot in ctx so the handler can fill it. -func ContextRegisterMoveResultSlot(ctx context.Context, slot *MoveResultSlot) context.Context { - return context.WithValue(ctx, moveResultSlotKey, slot) +// ContextRegisterMoveResultSlot installs an empty slot in ctx so that the +// storage driver can write move metadata via ContextSetMoveResult and the +// events middleware can read it via ContextGetMoveResult after the handler +// returns. Subsequent registrations are no-ops; the first registration wins. +func ContextRegisterMoveResultSlot(ctx context.Context) context.Context { + if ctx.Value(moveResultSlotKey) != nil { + return ctx + } + return context.WithValue(ctx, moveResultSlotKey, &moveResultSlot{}) } -// ContextSetMoveResult fills the slot registered in ctx with the given result. +// ContextSetMoveResult writes r into the slot. Subsequent writes overwrite +// the previous value. Does nothing if no slot was registered. func ContextSetMoveResult(ctx context.Context, r *storage.MoveResult) { - if slot, ok := ctx.Value(moveResultSlotKey).(*MoveResultSlot); ok { - slot.Result = r + if slot, ok := ctx.Value(moveResultSlotKey).(*moveResultSlot); ok { + slot.result = r } } + +// ContextGetMoveResult returns the move result written by the storage driver, +// or nil if none was set. +func ContextGetMoveResult(ctx context.Context) *storage.MoveResult { + if slot, ok := ctx.Value(moveResultSlotKey).(*moveResultSlot); ok { + return slot.result + } + return nil +} + +// --- delete result --- + +type deleteResultSlot struct { + result *storage.DeleteResult +} + +// ContextRegisterDeleteResultSlot installs an empty slot in ctx so that the +// storage driver can write delete metadata via ContextSetDeleteResult and the +// events middleware can read it via ContextGetDeleteResult after the handler +// returns. Subsequent registrations are no-ops; the first registration wins. +func ContextRegisterDeleteResultSlot(ctx context.Context) context.Context { + if ctx.Value(deleteResultSlotKey) != nil { + return ctx + } + return context.WithValue(ctx, deleteResultSlotKey, &deleteResultSlot{}) +} + +// ContextSetDeleteResult writes r into the slot. Subsequent writes overwrite +// the previous value. Does nothing if no slot was registered. +func ContextSetDeleteResult(ctx context.Context, r *storage.DeleteResult) { + if slot, ok := ctx.Value(deleteResultSlotKey).(*deleteResultSlot); ok { + slot.result = r + } +} + +// ContextGetDeleteResult returns the delete result written by the storage +// driver, or nil if none was set. +func ContextGetDeleteResult(ctx context.Context) *storage.DeleteResult { + if slot, ok := ctx.Value(deleteResultSlotKey).(*deleteResultSlot); ok { + return slot.result + } + return nil +} + +// --- delete storage space result --- + +type deleteStorageSpaceResultSlot struct { + result *storage.DeleteStorageSpaceResult +} + +// ContextRegisterDeleteStorageSpaceResultSlot installs an empty slot in ctx so +// that the storage driver can write delete-space metadata via +// ContextSetDeleteStorageSpaceResult and the events middleware can read it via +// ContextGetDeleteStorageSpaceResult after the handler returns. Subsequent +// registrations are no-ops; the first registration wins. +func ContextRegisterDeleteStorageSpaceResultSlot(ctx context.Context) context.Context { + if ctx.Value(deleteStorageSpaceResultSlotKey) != nil { + return ctx + } + return context.WithValue(ctx, deleteStorageSpaceResultSlotKey, &deleteStorageSpaceResultSlot{}) +} + +// ContextSetDeleteStorageSpaceResult writes r into the slot. Subsequent writes +// overwrite the previous value. Does nothing if no slot was registered. +func ContextSetDeleteStorageSpaceResult(ctx context.Context, r *storage.DeleteStorageSpaceResult) { + if slot, ok := ctx.Value(deleteStorageSpaceResultSlotKey).(*deleteStorageSpaceResultSlot); ok { + slot.result = r + } +} + +// ContextGetDeleteStorageSpaceResult returns the delete-space result written by +// the storage driver, or nil if none was set. +func ContextGetDeleteStorageSpaceResult(ctx context.Context) *storage.DeleteStorageSpaceResult { + if slot, ok := ctx.Value(deleteStorageSpaceResultSlotKey).(*deleteStorageSpaceResultSlot); ok { + return slot.result + } + return nil +} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/upload/asyncconf.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/upload/asyncconf.go new file mode 100644 index 0000000000..4c4bf802be --- /dev/null +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/upload/asyncconf.go @@ -0,0 +1,59 @@ +package upload + +import ( + "time" + + "github.com/go-viper/mapstructure/v2" +) + +// AsyncConf is how a service asks for async uploads: whether they are enabled, +// and the consumer subscription to use if they are. +type AsyncConf struct { + Enabled bool + ConsumerGroup string + NumConsumers int + // MountID is the storage id this provider answers for, used to drop + // postprocessing events belonging to other storages. + MountID string + CommitMaxRetries int + CommitRetryBackoff time.Duration +} + +// AsyncConfFromDriverConf reads the postprocessing settings off the driver's own +// config keys, so the coordinator and the driver cannot disagree about them. +func AsyncConfFromDriverConf(driverConf map[string]interface{}) AsyncConf { + if driverConf == nil { + return AsyncConf{} + } + var ac struct { + AsyncFileUploads bool `mapstructure:"asyncfileuploads"` + MountID string `mapstructure:"mount_id"` + Events struct { + NumConsumers int `mapstructure:"numconsumers"` + ConsumerGroup string `mapstructure:"consumer_group"` + CommitMaxRetries int `mapstructure:"commit_max_retries"` + CommitRetryBackoff time.Duration `mapstructure:"commit_retry_backoff"` + } `mapstructure:"events"` + } + _ = mapstructure.Decode(driverConf, &ac) + group := ac.Events.ConsumerGroup + if group == "" { + group = "dcfs" + } + maxRetries := ac.Events.CommitMaxRetries + if maxRetries <= 0 { + maxRetries = 3 + } + retryBackoff := ac.Events.CommitRetryBackoff + if retryBackoff <= 0 { + retryBackoff = 5 * time.Second + } + return AsyncConf{ + Enabled: ac.AsyncFileUploads, + ConsumerGroup: group, + NumConsumers: ac.Events.NumConsumers, + MountID: ac.MountID, + CommitMaxRetries: maxRetries, + CommitRetryBackoff: retryBackoff, + } +} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/upload/coordinator.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/upload/coordinator.go new file mode 100644 index 0000000000..b26b304f03 --- /dev/null +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/upload/coordinator.go @@ -0,0 +1,1048 @@ +package upload + +import ( + "context" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "strings" + "time" + + user "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" + provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" + "github.com/google/uuid" + "github.com/rs/zerolog" + tusd "github.com/tus/tusd/v2/pkg/handler" + + "github.com/opencloud-eu/reva/v2/pkg/appctx" + ctxpkg "github.com/opencloud-eu/reva/v2/pkg/ctx" + "github.com/opencloud-eu/reva/v2/pkg/errtypes" + "github.com/opencloud-eu/reva/v2/pkg/events" + "github.com/opencloud-eu/reva/v2/pkg/rhttp/datatx/metrics" + "github.com/opencloud-eu/reva/v2/pkg/storage" + "github.com/opencloud-eu/reva/v2/pkg/storage/utils/chunking" + "github.com/opencloud-eu/reva/v2/pkg/utils" +) + +// Request carries the metadata of a non-resumable (PUT) upload. +type Request struct { + Ref *provider.Reference + Body io.ReadCloser + Length int64 +} + +// FinishedFunc is called once an upload has finished, so that the caller can +// publish a FileUploaded event through its own publisher. +type FinishedFunc func(spaceOwner, executant *user.UserId, ref *provider.Reference) + +// Coordinator owns the upload lifecycle: initiation, data transfer and listing. +type Coordinator interface { + // InitiateUpload returns the protocols and ids that bytes can be appended to. + InitiateUpload(ctx context.Context, ref *provider.Reference, uploadLength int64, metadata map[string]string) (map[string]string, error) + // GetUpload returns the session with the given id as a tusd upload. + GetUpload(ctx context.Context, id string) (tusd.Upload, error) + // UseIn registers the coordinator as the tusd data store. + UseIn(composer *tusd.StoreComposer) + // ListUploadSessions returns the upload sessions matching the given filter. + ListUploadSessions(ctx context.Context, filter storage.UploadSessionFilter) ([]storage.UploadSession, error) + // Upload writes the whole body of a non-resumable (PUT) upload and finishes it. + Upload(ctx context.Context, req Request, uff FinishedFunc) (*provider.ResourceInfo, error) + // StartPostprocessing subscribes to postprocessing results and enables async + // uploads. Call once, before serving requests. + StartPostprocessing(stream events.Consumer, ac AsyncConf) error + // ResolveUpload stats the resource a finished upload produced, as the upload's executant. + storage.UploadSessionResolver +} + +const maxCommitRetryBackoff = 2 * time.Minute + +// coordinator is the concrete implementation of Coordinator. +type coordinator struct { + fs storage.FS + store SessionStore + chunkHandler *chunking.ChunkHandler + pub events.Publisher + // async defers the commit to postprocessing. Only StartPostprocessing sets it. + async bool + // mountID is the storage this coordinator serves, used to drop postprocessing + // events belonging to another one. + mountID string + commitMaxRetries int + commitRetryBackoff time.Duration +} + +// NewCoordinator constructs a coordinator backed by the given driver and store. +func NewCoordinator(fs storage.FS, store SessionStore, chunkFolder string, pub events.Publisher) *coordinator { + c := &coordinator{fs: fs, store: store, pub: pub} + if chunkFolder != "" { + c.chunkHandler = chunking.NewChunkHandler(chunkFolder) + } + return c +} + +// ResolveUpload stats the resource produced by a finished upload, reading it as the upload's +// executant. The session is reconstructed from the given tus FileInfo rather than the session +// store, so it still resolves after a synchronous upload has cleaned up its session. It returns +// the resource info and the executant context, so the caller can derive identity dependent +// values such as the WebDAV permissions. https://github.com/opencloud-eu/opencloud/issues/2409 +func (c *coordinator) ResolveUpload(ctx context.Context, info tusd.FileInfo) (*provider.ResourceInfo, context.Context, error) { + session := c.store.FromInfo(info) + ctx = session.Context(ctx) + ref := session.Reference() + ri, err := c.fs.GetMD(ctx, &ref, nil, nil) + return ri, ctx, err +} + +// NewCoordinatorFromConfig sets up a coordinator and its file store. Pass +// withChunking=false when only initiating uploads: chunk assembly happens on the +// data path, so the storageprovider doesn't need it. +func NewCoordinatorFromConfig(uploadDir string, driverConf map[string]interface{}, fs storage.FS, pub events.Publisher, log *zerolog.Logger, withChunking bool) (Coordinator, error) { + store := NewFileStoreFromConfig(uploadDir, driverConf, log) + if store == nil { + return nil, fmt.Errorf("cannot determine the upload directory, set upload_directory") + } + if err := store.Setup(); err != nil { + return nil, fmt.Errorf("upload directory setup failed: %w", err) + } + chunkFolder := "" + if withChunking { + chunkFolder = store.UploadDir() + } + return NewCoordinator(fs, store, chunkFolder, pub), nil +} + +// InitiateUpload resolves the target, then creates and persists the session that +// bytes are appended to. +func (c *coordinator) InitiateUpload(ctx context.Context, ref *provider.Reference, uploadLength int64, metadata map[string]string) (map[string]string, error) { + t, err := c.resolveTarget(ctx, ref, uploadLength, metadata) + if err != nil { + return nil, err + } + + session := c.store.New(ctx) + if err := c.populateSession(ctx, session, t, uploadLength, metadata); err != nil { + return nil, err + } + + if err := session.TouchBin(); err != nil { + return nil, fmt.Errorf("coordinator: could not create bin file: %w", err) + } + if err := session.Persist(ctx); err != nil { + session.Cleanup(ctx, true, true) + return nil, fmt.Errorf("coordinator: could not persist session: %w", err) + } + + metrics.UploadSessionsInitiated.Inc() + + // A zero-length upload has no bytes to append, so finish it here. + if uploadLength == 0 { + if _, err := c.finishUpload(ctx, session); err != nil { + return nil, err + } + } + + return map[string]string{ + "simple": session.ID(), + "tus": session.ID(), + }, nil +} + +// populateSession writes the resolved target and the request's metadata into a +// new session. +func (c *coordinator) populateSession(ctx context.Context, session Session, t *uploadTarget, uploadLength int64, metadata map[string]string) error { + session.SetMetadata("filename", t.name) + session.SetStorageValue("NodeName", t.name) + session.SetMetadata("dir", t.dir) + session.SetStorageValue("Dir", t.dir) + session.SetStorageValue("SpaceRoot", t.spaceID) + session.SetStorageValue("NodeParentId", t.parentID) + + if t.exists { + session.SetStorageValue("NodeId", t.nodeID) + session.SetStorageValue("NodeExists", "true") + } else { + // A new file has no id yet, and an empty one would resolve to the space root + // (lookup.go:191), so mint a placeholder TouchFile replaces. + session.SetStorageValue("NodeId", uuid.New().String()) + } + + if t.spaceOwner != nil { + session.SetStorageValue("SpaceOwnerOrManager", t.spaceOwner.GetOpaqueId()) + session.SetStorageValue("SpaceOwnerIdp", t.spaceOwner.GetIdp()) + session.SetStorageValue("SpaceOwnerType", utils.UserTypeToString(t.spaceOwner.GetType())) + } + if t.chunkName != "" { + session.SetStorageValue("Chunk", t.chunkName) + } + + // The ctx is gone by the time the bytes arrive, so record the actor now. + session.SetExecutant(ctxpkg.ContextMustGetUser(ctx)) + lockID, _ := ctxpkg.ContextGetLockID(ctx) + session.SetMetadata("lockid", lockID) + initiatorID, _ := ctxpkg.ContextGetInitiator(ctx) + session.SetMetadata("initiatorid", initiatorID) + + session.SetSize(uploadLength) + + return c.applyRequestMetadata(session, metadata) +} + +// applyRequestMetadata stores the client's upload metadata, rejecting a malformed +// checksum. Conditional headers are only recorded, and evaluated at finish. +func (c *coordinator) applyRequestMetadata(session Session, metadata map[string]string) error { + mtime, ok := metadata["mtime"] + if !ok || mtime == "null" { + mtime = utils.TimeToOCMtime(time.Now()) + } + session.SetMetadata("mtime", mtime) + + session.SetMetadata("providerID", metadata["providerID"]) + if v, ok := metadata["expires"]; ok && v != "null" { + session.SetMetadata("expires", v) + } + if _, ok := metadata["sizedeferred"]; ok { + session.SetSizeIsDeferred(true) + } + for _, key := range []string{"if-match", "if-none-match", "if-unmodified-since"} { + if v := metadata[key]; v != "" { + session.SetMetadata(key, v) + } + } + + checksum, ok := metadata["checksum"] + if !ok { + return nil + } + parts := strings.SplitN(checksum, " ", 2) + if len(parts) != 2 { + return errtypes.BadRequest("invalid checksum format. must be '[algorithm] [checksum]'") + } + switch parts[0] { + case "sha1", "md5", "adler32": + session.SetMetadata("checksum", checksum) + default: + return errtypes.BadRequest("unsupported checksum algorithm: " + parts[0]) + } + return nil +} + +// Upload writes the whole body of a non-resumable (PUT) upload and finishes it. +// req.Ref.Path carries the session id minted by InitiateUpload. +func (c *coordinator) Upload(ctx context.Context, req Request, uff FinishedFunc) (*provider.ResourceInfo, error) { + // The request path arrives rooted, while session ids are stored unrooted. + session, err := c.store.Get(ctx, strings.TrimPrefix(req.Ref.GetPath(), "/")) + if err != nil { + return nil, err + } + // Its bytes already arrived, and an async finish keeps the session for + // postprocessing: a repeated PUT would append to them and finish it again. + if session.Offset() > 0 { + return nil, errtypes.Aborted("coordinator: upload " + session.ID() + " was already received") + } + + // Behind the data gateway the request carries a transfer token, not the user. + ctx = session.Context(ctx) + + if chunk := session.Chunk(); chunk != "" { // legacy chunking v1 + if c.chunkHandler == nil { + return nil, errtypes.NotSupported("coordinator: chunked uploads require a chunk folder") + } + assembled, assembledSize, done, aErr := c.chunkHandler.Assemble(chunk, req.Body) + if aErr != nil { + return nil, aErr + } + if !done { + // The bytes accumulate in the chunk folder, so this session holds nothing. + session.Cleanup(ctx, true, true) + return nil, errtypes.PartialContent(req.Ref.String()) + } + defer assembled.Close() + // The declared length covers only the final chunk. + req.Body, req.Length = assembled, assembledSize + session.SetSize(assembledSize) + } + + size, err := session.WriteChunk(ctx, 0, req.Body) + if err != nil { + return nil, err + } + if size != req.Length { + return nil, errtypes.PartialContent("coordinator: unexpected end of stream") + } + + ri, err := c.finishUpload(ctx, session) + if err != nil { + return nil, err + } + + if uff != nil { + executant := session.Executant() + uff(session.SpaceOwner(), &executant, c.uploadRef(session)) + } + return ri, nil +} + +// finishUpload creates the node, validates the staged bytes and commits them, or +// hands them to postprocessing. +func (c *coordinator) finishUpload(ctx context.Context, session Session) (*provider.ResourceInfo, error) { + // a client that goes away must not leave the upload half finished + ctx = context.WithoutCancel(ctx) + // Only the staged bytes are read, so a mismatch has no node to undo. + if err := verifyAndStoreChecksums(ctx, session); err != nil { + session.Cleanup(ctx, true, true) + return nil, err + } + // Read before the node exists, so bad request metadata has no node to undo either. + info, err := uploadInfo(session) + if err != nil { + session.Cleanup(ctx, true, true) + return nil, err + } + // A driver whose PrepareUpload creates a new file's node is told where it goes, + // under the id minted at initiate. Any other is handed one TouchFile created. + if !session.NodeExists() && c.prepareCreatesNode() { + info.ParentID, info.Name = session.NodeParentID(), session.Filename() + } else if err := c.touchNode(ctx, session); err != nil { + return nil, err + } + + metrics.UploadSessionsBytesReceived.Inc() + + // Without a publisher there is nothing to hand the bytes to, so commit inline. + inline := !c.async || c.pub == nil || session.Size() == 0 + if inline { + // A driver that can store the bytes before the node points to them does so + // in PrepareUpload, then the node is never marked as processing. Only the + // path: a driver that wants a reader opens it, most ignore the source. + info.Source = &storage.UploadSource{Path: session.BinPath(), Length: session.Size()} + } + + committed, err := c.prepare(ctx, session, info) + if err != nil { + return nil, err + } + if committed { + return c.finished(ctx, session), nil + } + + if !inline { + if err := c.publishBytesReceived(ctx, session); err != nil { + c.rollbackPrepared(ctx, session, session.SizeDiff()) + return nil, err + } + // The node stays flagged and the staged bytes are kept: postprocessing needs + // both to finish later. + return c.uploadedResourceInfo(ctx, session), nil + } + + return c.finishSync(ctx, session) +} + +// publishBytesReceived hands the staged upload to postprocessing, which downloads +// the bytes from a signed URL to scan them before they are committed. +func (c *coordinator) publishBytesReceived(ctx context.Context, session Session) error { + url, err := session.URL(ctx) + if err != nil { + return err + } + + return events.Publish(ctx, c.pub, events.BytesReceived{ + UploadID: session.ID(), + URL: url, + SpaceOwner: session.SpaceOwner(), + ExecutingUser: session.ExecutantUser(), + ResourceID: &provider.ResourceId{ + StorageId: session.ProviderID(), + SpaceId: session.SpaceID(), + OpaqueId: session.NodeID(), + }, + Filename: session.Filename(), + Filesize: uint64(session.Size()), + ImpersonatingUser: impersonatingUser(ctx), + }) +} + +// prepareCreatesNode reports whether the driver's PrepareUpload creates a new +// file's node, sparing the extra metadata write a TouchFile costs. +func (c *coordinator) prepareCreatesNode() bool { + nc, ok := c.fs.(storage.NodeCreator) + return ok && nc.PrepareCreatesNode() +} + +// touchNode creates the node a new file's upload writes to. +func (c *coordinator) touchNode(ctx context.Context, session Session) error { + if session.NodeExists() { + return nil + } + + // The node has no id yet, so address it as a named child of its parent. + pathRef := &provider.Reference{ + ResourceId: &provider.ResourceId{ + SpaceId: session.SpaceID(), + OpaqueId: session.NodeParentID(), + }, + Path: session.Filename(), + } + // PrepareUpload marks and propagates the node, so TouchFile need not. + _, err := c.fs.TouchFile(storage.ContextSkipTouchPropagation(ctx), pathRef, false, session.Metadata()["mtime"]) + if err == nil { + // Not every driver reports the node it created, read it back. + var ri *provider.ResourceInfo + ri, err = c.fs.GetMD(ctx, pathRef, nil, nil) + if err == nil { + // Replaces the placeholder minted at initiate. + session.SetStorageValue("NodeId", ri.GetId().GetOpaqueId()) + session.SetStorageValue("SpaceRoot", ri.GetId().GetSpaceId()) + if ri.GetOwner() != nil { + if owner := c.spaceOwnerOrManager(ctx, ri.GetOwner(), ri.GetId().GetSpaceId()); owner != nil { + session.SetStorageValue("SpaceOwnerOrManager", owner.GetOpaqueId()) + session.SetStorageValue("SpaceOwnerIdp", owner.GetIdp()) + session.SetStorageValue("SpaceOwnerType", utils.UserTypeToString(owner.GetType())) + } + } + return nil + } + } + session.Cleanup(ctx, true, true) + if _, ok := err.(errtypes.IsNotFound); ok { + // The parent went away, or the share was revoked, while bytes were in flight. + return errtypes.PreconditionFailed(err.Error()) + } + return err +} + +// prepare has the driver write the node metadata, mark it as processing so clients +// do not read it before its bytes are committed, and snapshot the previous version, +// ahead of the commit that writes the bytes. It reports whether the driver already +// stored the bytes from info.Source, which leaves nothing to commit. +func (c *coordinator) prepare(ctx context.Context, session Session, info storage.UploadInfo) (bool, error) { + ref := session.Reference() + + // A failed PrepareUpload has already undone its own writes, a new file's node + // included, and marks the node only on success: there is nothing to unmark. + prepared, err := c.fs.PrepareUpload(ctx, &ref, session.ID(), info) + if err != nil { + if errors.Is(err, storage.ErrSourceNotStored) { + // Keep the staged bytes, like after a failed commit: they are the only + // copy of the upload, and the failure may be transient. + session.SetStatus(SessionStatusFailed, "commit failed: "+err.Error()) + if perr := session.Persist(ctx); perr != nil { + appctx.GetLogger(ctx).Error().Err(perr).Str("uploadid", session.ID()).Msg("could not persist the failed session") + } + return false, err + } + session.Cleanup(ctx, true, true) + if _, ok := err.(errtypes.IsNotFound); ok && info.ParentID != "" { + // The parent went away, or the share was revoked, while bytes were in flight. + return false, errtypes.PreconditionFailed(err.Error()) + } + return false, err + } + + if prepared.SpaceOwner != nil { + session.SetStorageValue("SpaceOwnerOrManager", prepared.SpaceOwner.GetOpaqueId()) + session.SetStorageValue("SpaceOwnerIdp", prepared.SpaceOwner.GetIdp()) + session.SetStorageValue("SpaceOwnerType", utils.UserTypeToString(prepared.SpaceOwner.GetType())) + } + session.SetSizeDiff(prepared.SizeDiff) + session.SetVersionCreated(prepared.VersionCreated) + if prepared.Committed { + // the upload is complete, the session is about to be removed + return true, nil + } + metrics.UploadProcessing.Inc() + + // Persisted, not just held: the commit may run in another process, which can + // only learn these, and the real node id from touchNode, by reading them back. + // Saved once, here: a failure now finds the node marked, so the rollback can + // purge it. + session.SetStatus(SessionStatusProcessing, "") + if err := session.Persist(ctx); err != nil { + c.rollbackPrepared(ctx, session, prepared.SizeDiff) + return false, err + } + return false, nil +} + +// rollbackInfo describes the upload to undo. The ids come from the session, which +// is the only place they survive a node whose own metadata has become unreadable. +func rollbackInfo(session Session, sizeDiff int64) storage.RollbackInfo { + return storage.RollbackInfo{ + NodeExisted: session.NodeExists(), + SizeDiff: sizeDiff, + NodeID: session.NodeID(), + ParentID: session.NodeParentID(), + Filename: session.Filename(), + Size: session.Size(), + } +} + +// rollbackPrepared undoes a finish that failed after PrepareUpload succeeded. +func (c *coordinator) rollbackPrepared(ctx context.Context, session Session, sizeDiff int64) { + ref := session.Reference() + // Before unmarking: RollbackUpload keys off the processing id to confirm the + // node is still this upload's. + if err := c.fs.RollbackUpload(ctx, &ref, session.ID(), rollbackInfo(session, sizeDiff)); err != nil { + // The session is the last record of what to undo, so keep it for a retry + // rather than leaving the quota consumed with nothing to reclaim it from. + appctx.GetLogger(ctx).Error().Err(err).Str("uploadid", session.ID()).Msg("could not roll back upload, keeping session") + return + } + c.unmarkProcessing(ctx, session, &ref) + metrics.UploadProcessing.Dec() + session.Cleanup(ctx, true, true) +} + +// unmarkProcessing clears the processing flag, tolerating a node the rollback +// already purged. +func (c *coordinator) unmarkProcessing(ctx context.Context, session Session, ref *provider.Reference) { + err := c.fs.MarkProcessing(ctx, ref, false, session.ID()) + log := appctx.GetLogger(ctx).With().Str("uploadid", session.ID()).Logger() + switch err.(type) { + case nil: + case errtypes.IsNotFound: + // RollbackUpload purged the node this upload created. + log.Debug().Err(err).Msg("could not unmark processing") + default: + log.Error().Err(err).Msg("could not unmark processing") + } +} + +// uploadInfo collects what the driver needs to write the node metadata. The +// preconditions are re-checked there, because the resource may have changed while +// the bytes were being uploaded. +func uploadInfo(session Session) (storage.UploadInfo, error) { + md := session.Metadata() + info := storage.UploadInfo{ + NodeExisted: session.NodeExists(), + Size: session.Size(), + Checksums: session.Checksums(), + IfMatch: md["if-match"], + IfNoneMatch: md["if-none-match"], + } + if v := md["mtime"]; v != "" { + mtime, err := utils.MTimeToTime(v) + if err != nil { + return info, errtypes.BadRequest("coordinator: invalid mtime: " + v) + } + info.MTime = mtime + } + if v := md["if-unmodified-since"]; v != "" { + ius, err := time.Parse(time.RFC3339Nano, v) + if err != nil { + return info, errtypes.BadRequest("coordinator: invalid if-unmodified-since: " + v) + } + info.IfUnmodifiedSince = ius + } + return info, nil +} + +// verifyAndStoreChecksums hashes the staged bytes, checks them against the +// checksum the client announced, and stores them for the commit. +func verifyAndStoreChecksums(ctx context.Context, session Session) error { + sha1h, md5h, adler32h, err := calculateChecksums(ctx, session.BinPath()) + if err != nil { + return err + } + + // The announced checksum is not in Metadata(), so read the raw info. + info, err := session.GetInfo(ctx) + if err != nil { + return err + } + if checksum := info.MetaData["checksum"]; checksum != "" { + parts := strings.SplitN(checksum, " ", 2) + if len(parts) != 2 { + return errtypes.BadRequest("invalid checksum format. must be '[algorithm] [checksum]'") + } + var checkErr error + switch parts[0] { + case "sha1": + checkErr = checkHash(parts[1], sha1h) + case "md5": + checkErr = checkHash(parts[1], md5h) + case "adler32": + checkErr = checkHash(parts[1], adler32h) + default: + checkErr = errtypes.BadRequest("unsupported checksum algorithm: " + parts[0]) + } + if checkErr != nil { + return checkErr + } + } + + session.SetChecksums(sha1h.Sum(nil), md5h.Sum(nil), adler32h.Sum(nil)) + return nil +} + +// finishSync commits the staged bytes for an inline upload, discarding the +// session if the commit fails: the client is still waiting and will retry, so +// keeping the bytes would only leak them. +func (c *coordinator) finishSync(ctx context.Context, session Session) (*provider.ResourceInfo, error) { + ri, err := c.commit(ctx, session) + if err != nil { + // Keep the staged bytes: they are the only copy of the upload, and the + // failure may be transient. + c.rollbackNode(ctx, session, "commit failed: "+err.Error()) + metrics.UploadProcessing.Dec() + return nil, err + } + return ri, nil +} + +// finishAsync commits the staged bytes for an upload postprocessing has cleared, +// retrying transient failures with capped exponential backoff. On exhaustion +// the caller is responsible for rolling back the node and publishing the failure. +func (c *coordinator) finishAsync(ctx context.Context, session Session) error { + maxAttempts := c.commitMaxRetries + 1 + backoff := c.commitRetryBackoff + var err error + for attempt := 1; attempt <= maxAttempts; attempt++ { + if _, err = c.commit(ctx, session); err == nil { + return nil + } + ev := appctx.GetLogger(ctx).Warn().Err(err). + Int("attempt", attempt).Int("maxAttempts", maxAttempts). + Str("uploadid", session.ID()). + Str("spaceid", session.SpaceID()).Str("nodeid", session.NodeID()) + if attempt == maxAttempts { + ev.Msg("blob commit failed, giving up") + break + } + backoff = min(backoff, maxCommitRetryBackoff) + ev.Dur("backoff", backoff).Msg("blob commit failed, retrying after backoff") + t := time.NewTimer(backoff) + select { + case <-ctx.Done(): + t.Stop() + return ctx.Err() + case <-t.C: + } + backoff *= 2 + } + return err +} + +// commit writes the staged bytes through the driver seam and, on success, unmarks +// the node and retires the session. It leaves a failure untouched for the caller +// to handle, the two finish paths wanting opposite things. +func (c *coordinator) commit(ctx context.Context, session Session) (*provider.ResourceInfo, error) { + ref := session.Reference() + + f, err := os.Open(session.BinPath()) + if err != nil { + return nil, err + } + // The verdict rides along with the bytes, so a committed blob always carries + // the one it was cleared under. Empty on the inline path, which never scans. + scanResult, scanDate := session.ScanData() + + // CommitUpload does not own the body; we opened it, so we close it. The path + // lets a driver that can move the staged file into place skip the copy. + err = c.fs.CommitUpload(ctx, &ref, session.ID(), storage.UploadSource{ + Body: f, + Path: session.BinPath(), + Length: session.Size(), + ScanResult: scanResult, + ScanDate: scanDate, + }) + f.Close() + if err != nil { + return nil, err + } + + // Not unmarkProcessing: the commit succeeded, so a missing node is unexpected. + if err := c.fs.MarkProcessing(ctx, &ref, false, session.ID()); err != nil { + appctx.GetLogger(ctx).Error().Err(err).Str("uploadid", session.ID()).Msg("could not unmark processing") + } + metrics.UploadProcessing.Dec() + return c.finished(ctx, session), nil +} + +// finished retires the session of a complete upload and announces it. +func (c *coordinator) finished(ctx context.Context, session Session) *provider.ResourceInfo { + session.Cleanup(ctx, true, true) + metrics.UploadSessionsFinalized.Inc() + + ri := c.uploadedResourceInfo(ctx, session) + c.publishUploadReady(ctx, session, ri) + return ri +} + +// uploadedResourceInfo describes the uploaded resource for the caller, which turns +// it into PUT response headers. +// +// TODO: the fallback carries no etag, which a write-only share used to get. +// Returning it through the seam is the proper fix. +func (c *coordinator) uploadedResourceInfo(ctx context.Context, session Session) *provider.ResourceInfo { + ref := session.Reference() + // The driver owns the resulting etag and mtime, so read them back. + ri, err := c.fs.GetMD(ctx, &ref, nil, nil) + if err == nil { + // Drivers do not know their own mount id and the dataprovider does not stamp + // it, so an unstamped id would not resolve for the client. + if ri.GetId().GetStorageId() == "" { + ri.Id.StorageId = session.ProviderID() + } + return ri + } + + // GetMD is permission-gated, so a write-only share cannot stat what it just + // uploaded. That must not fail the upload. + appctx.GetLogger(ctx).Debug().Err(err).Str("uploadid", session.ID()).Msg("could not stat uploaded resource") + fallback := &provider.ResourceInfo{Id: ref.GetResourceId(), Size: uint64(session.Size())} + if mtime, mErr := utils.MTimeToTime(session.Metadata()["mtime"]); mErr == nil { + fallback.Mtime = utils.TimeToTS(mtime) + } + return fallback +} + +// publishUploadReady announces that the file is available. Consumers such as the +// search indexer only listen for UploadReady, so without it they would never learn +// about an upload the coordinator committed inline. +func (c *coordinator) publishUploadReady(ctx context.Context, session Session, ri *provider.ResourceInfo) { + if c.pub == nil { + return + } + if err := events.Publish(ctx, c.pub, events.UploadReady{ + UploadID: session.ID(), + Filename: session.Filename(), + SpaceOwner: session.SpaceOwner(), + ExecutingUser: session.ExecutantUser(), + FileRef: c.uploadRef(session), + ResourceID: ri.GetId(), + ParentID: &provider.ResourceId{ + StorageId: session.ProviderID(), + SpaceId: session.SpaceID(), + OpaqueId: session.NodeParentID(), + }, + Timestamp: utils.TSNow(), + IsVersion: session.VersionCreated(), + ImpersonatingUser: impersonatingUser(ctx), + }); err != nil { + appctx.GetLogger(ctx).Error().Err(err).Str("uploadid", session.ID()).Msg("failed to publish UploadReady event") + } +} + +// uploadTarget is what an upload needs to know about its destination +type uploadTarget struct { + // exists distinguishes an overwrite from a new file. + exists bool + // chunkName is set for legacy chunking-v1 uploads only. + chunkName string + + nodeID string + spaceID string + parentID string + dir string + name string + spaceOwner *user.UserId +} + +// resolveTarget locates the file an upload writes to, and rejects an upload that +// may not proceed. +func (c *coordinator) resolveTarget(ctx context.Context, ref *provider.Reference, uploadLength int64, metadata map[string]string) (*uploadTarget, error) { + t := &uploadTarget{} + if chunking.IsChunked(ref.GetPath()) { // check legacy chunking v1 + var err error + ref, t.chunkName, err = rewriteChunkedRef(ref) + if err != nil { + return nil, err + } + } + + // TODO: GetMD reports a file hidden by a deny-grant as NotFound, so the upload + // fails late with 409 instead of 403. Needs a permission-free resolve. + existing, err := c.fs.GetMD(ctx, ref, []string{}, []string{}) + switch err.(type) { + case nil: + t.exists = true + case errtypes.IsNotFound: + t.exists = false + default: + return nil, err + } + + if err := c.checkQuota(ctx, ref, uploadLength, existing); err != nil { + return nil, err + } + + if t.exists { + if err := c.describeExisting(ctx, ref, existing, metadata, t); err != nil { + return nil, err + } + } else if err := c.describeNew(ctx, ref, t); err != nil { + return nil, err + } + + if t.name == "" { + return nil, errtypes.BadRequest("coordinator: missing filename in ref") + } + if t.dir == "" { + return nil, errtypes.BadRequest("coordinator: could not determine upload directory") + } + return t, nil +} + +// checkQuota rejects an upload that would not fit in the space, counting only +// the bytes it adds. +func (c *coordinator) checkQuota(ctx context.Context, ref *provider.Reference, uploadLength int64, existing *provider.ResourceInfo) error { + if uploadLength < 0 { + return nil + } + spaceRef := &provider.Reference{ResourceId: &provider.ResourceId{ + StorageId: ref.GetResourceId().GetStorageId(), + SpaceId: ref.GetResourceId().GetSpaceId(), + }} + _, _, remaining, err := c.fs.GetQuota(ctx, spaceRef) + if err != nil { + return nil + } + + netRequired := uint64(uploadLength) + if existingSize := existing.GetSize(); existingSize < netRequired { + netRequired -= existingSize + } else { + netRequired = 0 + } + if remaining < netRequired { + return errtypes.InsufficientStorage("quota exceeded") + } + return nil +} + +// describeExisting fills in the target from the file being overwritten. +func (c *coordinator) describeExisting(ctx context.Context, ref *provider.Reference, existing *provider.ResourceInfo, metadata map[string]string, t *uploadTarget) error { + if !existing.GetPermissionSet().GetInitiateFileUpload() { + return errtypes.PermissionDenied(ref.GetPath()) + } + if existing.GetType() == provider.ResourceType_RESOURCE_TYPE_CONTAINER { + return errtypes.PreconditionFailed("resource is not a file") + } + + t.nodeID = existing.GetId().GetOpaqueId() + t.spaceID = existing.GetId().GetSpaceId() + t.parentID = existing.GetParentId().GetOpaqueId() + t.name = existing.GetName() + t.spaceOwner = c.spaceOwnerOrManager(ctx, existing.GetOwner(), t.spaceID) + + // GetMD returns only the basename for id-based refs, so ask for the full path. + relPath := existing.GetPath() + if utils.IsRelativeReference(ref) { + if full, err := c.fs.GetPathByID(ctx, existing.GetId()); err == nil { + relPath = full + } + } + t.dir = filepath.Dir(relPath) + + // Lock before precondition, the order main checks them in (upload.go:293-302). + if err := c.checkLock(ctx, ref); err != nil { + return err + } + if metadata["if-none-match"] == "*" { + return errtypes.Aborted(fmt.Sprintf("parent %s already has a child %s, id %s", t.parentID, t.name, t.nodeID)) + } + return nil +} + +// spaceOwnerOrManager resolves the space owner, falling back to a manager. +func (c *coordinator) spaceOwnerOrManager(ctx context.Context, owner *user.UserId, spaceID string) *user.UserId { + // A space with no personal owner stores a SPACE_OWNER placeholder (spaces.go:145). + if owner != nil && owner.GetType() != user.UserType_USER_TYPE_SPACE_OWNER { + return owner + } + + grants, err := c.fs.ListGrants(ctx, &provider.Reference{ResourceId: &provider.ResourceId{ + SpaceId: spaceID, + OpaqueId: spaceID, + }}) + if err != nil { + return nil + } + + // Grants come back in map order, so several managers resolve to an arbitrary one. + for _, g := range grants { + // Group grants carry no user id. + uid := g.GetGrantee().GetUserId() + if uid == nil { + continue + } + p := g.GetPermissions() + if p.GetStat() && p.GetListContainer() && p.GetInitiateFileDownload() { + return uid + } + } + return nil +} + +// checkLock rejects an upload that conflicts with a lock held on the file. +func (c *coordinator) checkLock(ctx context.Context, ref *provider.Reference) error { + // An unlocked file and a driver without locks both error, so only a lock we + // actually read counts as one. + diskLock, err := c.fs.GetLock(ctx, ref) + if err != nil { + diskLock = nil + } + contextLockID, _ := ctxpkg.ContextGetLockID(ctx) + + switch { + case diskLock == nil && contextLockID != "": + return errtypes.Aborted("not locked") + case diskLock == nil: + return nil + case contextLockID == "": + return errtypes.Locked(diskLock.LockId) + case contextLockID != diskLock.LockId: + return errtypes.Aborted("mismatching lock") + } + return nil +} + +// describeNew fills in the target for a file that does not exist yet, from its +// parent directory. +func (c *coordinator) describeNew(ctx context.Context, ref *provider.Reference, t *uploadTarget) error { + t.spaceID = ref.GetResourceId().GetSpaceId() + t.dir = filepath.Dir(ref.GetPath()) + t.name = filepath.Base(ref.GetPath()) + + parentRef := &provider.Reference{ResourceId: ref.GetResourceId(), Path: t.dir} + parentMD, err := c.fs.GetMD(ctx, parentRef, []string{}, []string{}) + switch err.(type) { + case nil: + case errtypes.IsNotFound: + return c.missingParentError(ctx, ref, t.dir, err) + default: + return err + } + + if !parentMD.GetPermissionSet().GetInitiateFileUpload() { + return errtypes.PermissionDenied(ref.GetPath()) + } + t.parentID = parentMD.GetId().GetOpaqueId() + t.spaceID = parentMD.GetId().GetSpaceId() + + // An id-based ref yields a relative dir ("."), so ask for the parent's full path. + if utils.IsRelativeReference(ref) { + if parentPath, pErr := c.fs.GetPathByID(ctx, parentMD.GetId()); pErr == nil { + t.dir = parentPath + } + } + return nil +} + +// missingParentError tells a missing directory apart from one that is only +// invisible to the caller: a visible ancestor means it is missing. +func (c *coordinator) missingParentError(ctx context.Context, ref *provider.Reference, dir string, notFound error) error { + for ancestor := dir; ancestor != "." && ancestor != "/"; { + ancestor = filepath.Dir(ancestor) + ancestorRef := &provider.Reference{ResourceId: ref.GetResourceId(), Path: ancestor} + if _, err := c.fs.GetMD(ctx, ancestorRef, []string{}, []string{}); err == nil { + return errtypes.PreconditionFailed(notFound.Error()) + } + } + return errtypes.PermissionDenied(ref.GetPath()) +} + +// rewriteChunkedRef turns a legacy chunking-v1 path into a reference to the real +// target file, plus the chunk name. +func rewriteChunkedRef(ref *provider.Reference) (*provider.Reference, string, error) { + ci, err := chunking.GetChunkBLOBInfo(ref.GetPath()) + if err != nil { + return nil, "", errtypes.BadRequest(err.Error()) + } + return &provider.Reference{ResourceId: ref.ResourceId, Path: ci.Path}, filepath.Base(ref.GetPath()), nil +} + +// ListUploadSessions returns the upload sessions matching the given filter. +func (c *coordinator) ListUploadSessions(ctx context.Context, filter storage.UploadSessionFilter) ([]storage.UploadSession, error) { + // Only the driver can resolve a session's node, so the orphaned filter needs a + // driver that answers the question. Assert once rather than per session. + var orphanChecker storage.OrphanChecker + if filter.Orphaned != nil { + var ok bool + if orphanChecker, ok = c.fs.(storage.OrphanChecker); !ok { + return nil, errtypes.NotSupported("coordinator: the orphaned filter is not supported") + } + } + + var sessions []Session + if filter.ID != nil && *filter.ID != "" { + session, err := c.store.Get(ctx, *filter.ID) + if err != nil { + return nil, err + } + sessions = []Session{session} + } else { + var err error + sessions, err = c.store.List(ctx) + if err != nil { + return nil, err + } + } + + filtered := []storage.UploadSession{} + now := time.Now() + for _, session := range sessions { + if filter.Processing != nil && *filter.Processing != session.IsProcessing() { + continue + } + if filter.Expired != nil { + if *filter.Expired { + if now.Before(session.Expires()) { + continue + } + } else { + if now.After(session.Expires()) { + continue + } + } + } + if filter.HasVirus != nil { + sr, _ := session.ScanData() + infected := sr != "" + if *filter.HasVirus != infected { + continue + } + } + // evaluated last: unlike the other filters this reads the node metadata + // from disk, so it is only done for sessions that passed all other filters + if filter.Orphaned != nil { + ref := session.Reference() + if *filter.Orphaned != orphanChecker.IsOrphaned(ctx, &ref) { + continue + } + } + filtered = append(filtered, session) + } + return filtered, nil +} + +// uploadRef builds the reference upload events carry: the space root, plus the +// file's path within it. +func (c *coordinator) uploadRef(session Session) *provider.Reference { + return &provider.Reference{ + ResourceId: &provider.ResourceId{ + StorageId: session.ProviderID(), + SpaceId: session.SpaceID(), + OpaqueId: session.SpaceID(), + }, + Path: utils.MakeRelativePath(filepath.Join(session.Dir(), session.Filename())), + } +} + +// impersonatingUser returns the real actor behind a borrowed identity, which +// public link and OCM auth record in the request user's opaque. +func impersonatingUser(ctx context.Context) *user.User { + u, ok := ctxpkg.ContextGetUser(ctx) + if !ok || !utils.ExistsInOpaque(u.GetOpaque(), "impersonating-user") { + return nil + } + impersonating := &user.User{} + if err := utils.ReadJSONFromOpaque(u.GetOpaque(), "impersonating-user", impersonating); err != nil { + appctx.GetLogger(ctx).Error().Err(err).Msg("could not read impersonating user") + return nil + } + return impersonating +} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/upload/filestore.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/upload/filestore.go new file mode 100644 index 0000000000..3898705952 --- /dev/null +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/upload/filestore.go @@ -0,0 +1,210 @@ +package upload + +import ( + "context" + "encoding/json" + iofs "io/fs" + "os" + "path/filepath" + "strings" + "syscall" + + "github.com/go-viper/mapstructure/v2" + "github.com/google/uuid" + "github.com/pkg/errors" + "github.com/rs/zerolog" + tusd "github.com/tus/tusd/v2/pkg/handler" + + "github.com/opencloud-eu/reva/v2/pkg/appctx" +) + +// TokenOptions carries the JWT-signing configuration needed to produce transfer +// URLs for the postprocessing service. +type TokenOptions struct { + DownloadEndpoint string + DataGatewayEndpoint string + TransferSharedSecret string + TransferExpires int64 +} + +// SessionStore abstracts upload-session persistence for the Coordinator. +type SessionStore interface { + New(ctx context.Context) Session + Get(ctx context.Context, id string) (Session, error) + List(ctx context.Context) ([]Session, error) + // FromInfo wraps an upload's tus FileInfo without reading the store, so it also + // works after a synchronous upload has cleaned up its session. + FromInfo(info tusd.FileInfo) Session +} + +// FileStore is a filesystem-backed SessionStore. Sessions are stored as a pair +// of files in the upload directory: +// +// - .info — JSON-encoded tusd.FileInfo +// - — staged binary bytes +// +// This is the same on-disk format used by OcisStore so existing sessions +// survive a rolling deploy that switches to FileStore. +type FileStore struct { + uploadDir string + opts TokenOptions + log *zerolog.Logger +} + +// FileStoreFromDriverConf builds a FileStore from a reva driver config map. +// Returns nil if the config carries no upload path (driver does not support +// coordinated uploads). Each service that mounts the same driver calls this +// independently. +func FileStoreFromDriverConf(driverConf map[string]interface{}, log *zerolog.Logger) *FileStore { + if driverConf == nil { + return nil + } + + // storage_root is the ocm driver's spelling of root; it stages uploads under + // the same /uploads/ layout the decomposedfs family uses. + type driverRootConf struct { + Root string `mapstructure:"root"` + UploadDirectory string `mapstructure:"upload_directory"` + StorageRoot string `mapstructure:"storage_root"` + } + var rc driverRootConf + _ = mapstructure.Decode(driverConf, &rc) + + // upload_directory already names the upload directory itself, the way + // decomposedfs reads it (options.go:172, posix tree.go:168). The other two are + // storage roots that stage uploads in a subdirectory, so only they get joined. + if rc.UploadDirectory != "" { + return newFileStoreWithTokens(rc.UploadDirectory, driverConf, log) + } + + root := rc.Root + if root == "" { + root = rc.StorageRoot + } + if root == "" { + return nil + } + + return newFileStoreWithTokens(filepath.Join(root, "uploads"), driverConf, log) +} + +// NewFileStoreFromConfig builds a FileStore staging uploads in uploadDir when +// set, falling back to the active driver config. This allows drivers that have +// no local root (e.g. KW) to still get a coordinator by setting +// upload_directory at the service level rather than inside the driver. +// Returns nil only when neither source resolves to a non-empty path. +func NewFileStoreFromConfig(uploadDir string, driverConf map[string]interface{}, log *zerolog.Logger) *FileStore { + if uploadDir != "" { + // Still take the tokens from the driver config: they sign the transfer URL + // that postprocessing downloads the staged bytes from, and a service-level + // upload directory says nothing about them. + return newFileStoreWithTokens(uploadDir, driverConf, log) + } + return FileStoreFromDriverConf(driverConf, log) +} + +func newFileStoreWithTokens(uploadDir string, driverConf map[string]interface{}, log *zerolog.Logger) *FileStore { + type tokenConf struct { + DownloadEndpoint string `mapstructure:"download_endpoint"` + DataGatewayEndpoint string `mapstructure:"datagateway_endpoint"` + TransferSharedSecret string `mapstructure:"transfer_shared_secret"` + TransferExpires int64 `mapstructure:"transfer_expires"` + } + var tc tokenConf + if tokens, ok := driverConf["tokens"]; ok { + _ = mapstructure.Decode(tokens, &tc) + } + return NewFileStore(uploadDir, TokenOptions(tc), log) +} + +// NewFileStore creates a FileStore staging uploads in uploadDir. +// uploadDir must be on a shared filesystem when multiple pods handle the same space. +func NewFileStore(uploadDir string, opts TokenOptions, log *zerolog.Logger) *FileStore { + return &FileStore{uploadDir: uploadDir, opts: opts, log: log} +} + +// UploadDir returns the directory this FileStore stages uploads in. +func (fs *FileStore) UploadDir() string { + return fs.uploadDir +} + +// Setup creates the upload directory eagerly so permission problems are caught +// at startup rather than on the first upload. +func (fs *FileStore) Setup() error { + return os.MkdirAll(fs.uploadDir, 0700) +} + +// New allocates a fresh session with a new UUID. +func (fs *FileStore) New(_ context.Context) Session { + return &FileSession{ + store: fs, + info: tusd.FileInfo{ + ID: uuid.New().String(), + Storage: map[string]string{ + "Type": "OCISStore", + }, + MetaData: tusd.MetaData{ + "status": SessionStatusUploading, + }, + }, + } +} + +// FromInfo wraps an upload's tus FileInfo into a session without reading the store. +func (fs *FileStore) FromInfo(info tusd.FileInfo) Session { + return &FileSession{store: fs, info: info} +} + +// Get loads the session with the given id from disk. +func (fs *FileStore) Get(ctx context.Context, id string) (Session, error) { + infoPath := fileSessionPath(fs.uploadDir, id) + + data, err := os.ReadFile(infoPath) + if err != nil { + if pathErr, ok := err.(*os.PathError); ok && pathErr.Err == syscall.ESTALE { + return nil, tusd.ErrNotFound + } + if errors.Is(err, iofs.ErrNotExist) { + return nil, tusd.ErrNotFound + } + return nil, err + } + + var info tusd.FileInfo + if err := json.Unmarshal(data, &info); err != nil { + return nil, err + } + + session := &FileSession{store: fs, info: info} + + stat, err := os.Stat(session.binPath()) + if err != nil { + if os.IsNotExist(err) { + return nil, tusd.ErrNotFound + } + return nil, err + } + session.info.Offset = stat.Size() + + return session, nil +} + +// List returns all sessions found in the upload directory. +func (fs *FileStore) List(ctx context.Context) ([]Session, error) { + infoFiles, err := filepath.Glob(filepath.Join(fs.uploadDir, "*.info")) + if err != nil { + return nil, err + } + + sessions := make([]Session, 0, len(infoFiles)) + for _, path := range infoFiles { + id := strings.TrimSuffix(filepath.Base(path), ".info") + session, err := fs.Get(ctx, id) + if err != nil { + appctx.GetLogger(ctx).Error().Str("path", path).Err(err).Msg("filestore: could not load session") + continue + } + sessions = append(sessions, session) + } + return sessions, nil +} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/upload/postprocessing.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/upload/postprocessing.go new file mode 100644 index 0000000000..852cce825d --- /dev/null +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/upload/postprocessing.go @@ -0,0 +1,261 @@ +// This file holds the postprocessing result collector: the second half of an +// async upload. finishUpload stages the bytes and publishes BytesReceived; the +// postprocessing service scans them and reports back here, and only then are the +// bytes committed through the driver seam. +// +// It is driver-agnostic on purpose: this logic used to live inside decomposedfs, +// which meant only that driver could offer async uploads. + +package upload + +import ( + "context" + "errors" + + provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" + "github.com/rs/zerolog" + + "github.com/opencloud-eu/reva/v2/pkg/appctx" + ctxpkg "github.com/opencloud-eu/reva/v2/pkg/ctx" + "github.com/opencloud-eu/reva/v2/pkg/events" + "github.com/opencloud-eu/reva/v2/pkg/rhttp/datatx/metrics" + "github.com/opencloud-eu/reva/v2/pkg/utils" +) + +// RegisteredEvents are the postprocessing events the coordinator consumes. +var RegisteredEvents = []events.Unmarshaller{ + events.PostprocessingFinished{}, + events.PostprocessingStepFinished{}, + events.RestartPostprocessing{}, + events.StartPostprocessingStep{}, + events.CleanUpload{}, +} + +// StartPostprocessing subscribes to postprocessing results and switches the +// coordinator over to async uploads: from here on finished uploads stage their +// bytes and wait for a scan verdict instead of committing inline. +// +// The two go together on purpose. Deferring a commit is only safe if something +// will arrive to finish it, so there is no way to enable async without a running +// consumer, and none to run a consumer that never receives work. +// +// Call once, before serving requests. Fails without a publisher: nothing would +// hand uploads to postprocessing, so every one of them would wait for a verdict +// that never comes. +func (c *coordinator) StartPostprocessing(stream events.Consumer, ac AsyncConf) error { + if c.pub == nil { + return errors.New("coordinator: async uploads need an event publisher") + } + ch, err := events.Consume(stream, ac.ConsumerGroup, RegisteredEvents...) + if err != nil { + return err + } + numConsumers := ac.NumConsumers + if numConsumers <= 0 { + numConsumers = 1 + } + c.mountID = ac.MountID + c.commitMaxRetries = ac.CommitMaxRetries + c.commitRetryBackoff = ac.CommitRetryBackoff + c.async = true + for i := 0; i < numConsumers; i++ { + go c.Postprocessing(ch) + } + return nil +} + +// Postprocessing consumes postprocessing results until ch is closed. Run it in +// its own goroutine, one per configured consumer. +func (c *coordinator) Postprocessing(ch <-chan events.Event) { + for event := range ch { + // derive a per-event context from the event's W3C trace context so the + // postprocessing work is linked to the originating request + ctx := event.GetTraceContext(context.Background()) + ctx = ctxpkg.ContextSetInitiator(ctx, event.InitiatorID) + c.processEvent(ctx, event) + } +} + +// servesStorage reports whether an event is for the storage this coordinator +// serves. Postprocessing runs as a separate service and broadcasts its results to +// every storage provider, so each has to recognise its own. Events that name no +// storage predate this and are accepted. +func (c *coordinator) servesStorage(id *provider.ResourceId) bool { + if c.mountID == "" || id.GetStorageId() == "" { + return true + } + return id.GetStorageId() == c.mountID +} + +func (c *coordinator) processEvent(ctx context.Context, event events.Event) { + log := appctx.GetLogger(ctx) + + switch ev := event.Event.(type) { + case events.PostprocessingFinished: + if !c.servesStorage(ev.ResourceID) { + return + } + c.onPostprocessingFinished(ctx, ev, log) + case events.RestartPostprocessing: + c.onRestartPostprocessing(ctx, ev, log) + case events.StartPostprocessingStep: + if ev.UploadID == "" { + return + } + session, err := c.store.Get(ctx, ev.UploadID) + if err != nil { + // postprocessing broadcasts to every storage, the session may live elsewhere + log.Debug().Err(err).Str("uploadid", ev.UploadID).Msg("StartPostprocessingStep: could not load session") + return + } + session.SetStatus(SessionStatusProcessing, "started postprocessing step: "+string(ev.StepToStart)) + if err := session.Persist(ctx); err != nil { + log.Error().Err(err).Str("uploadid", ev.UploadID).Msg("could not persist the session status") + } + case events.CleanUpload: + session, err := c.store.Get(ctx, ev.UploadID) + if err != nil { + log.Error().Err(err).Str("uploadid", ev.UploadID).Msg("CleanUpload: could not load session") + return + } + if !ev.KeepUpload { + c.rollbackPrepared(ctx, session, session.SizeDiff()) + } else { + c.rollbackNode(ctx, session, "cleaned up, keeping the upload") + metrics.UploadProcessing.Dec() + } + case events.PostprocessingStepFinished: + if !c.servesStorage(ev.ResourceID) { + return + } + if ev.FinishedStep != events.PPStepAntivirus { + // only the antivirus result is recorded on the session + return + } + res, ok := ev.Result.(events.VirusscanResult) + if !ok || res.ErrorMsg != "" { + // the scan itself failed; PostprocessingFinished decides the outcome + return + } + session, err := c.store.Get(ctx, ev.UploadID) + if err != nil { + // an empty upload id means an on-demand scan, which has no session + if ev.UploadID != "" { + log.Error().Err(err).Str("uploadid", ev.UploadID).Msg("PostprocessingStepFinished: could not load session") + } + return + } + session.SetScanData(res.Description, res.Scandate) + switch ev.Outcome { + case events.PPOutcomeAbort, events.PPOutcomeDelete: + session.SetStatus(SessionStatusFailed, "finished postprocessing step: "+string(ev.FinishedStep)) + default: + session.SetStatus(SessionStatusProcessing, "finished postprocessing step: "+string(ev.FinishedStep)) + } + metrics.UploadSessionsScanned.Inc() + if err := session.Persist(ctx); err != nil { + log.Error().Err(err).Str("uploadid", ev.UploadID).Msg("could not persist scan result") + } + } +} + +// onPostprocessingFinished completes or discards an upload according to the +// outcome postprocessing reported. +func (c *coordinator) onPostprocessingFinished(ctx context.Context, ev events.PostprocessingFinished, log *zerolog.Logger) { + session, err := c.store.Get(ctx, ev.UploadID) + if err != nil { + // Without the session we cannot reach the staged bytes, so they are leaked + // here. Housekeeping cleans them up later. + log.Error().Err(err).Str("uploadid", ev.UploadID).Msg("PostprocessingFinished: could not load session") + return + } + ctx = session.Context(ctx) + log = appctx.GetLogger(ctx) + + switch ev.Outcome { + case events.PPOutcomeContinue: + if err := c.finishAsync(ctx, session); err != nil { + log.Error().Err(err).Str("uploadid", ev.UploadID).Msg("blob commit failed after all retries, reverting node and keeping bytes") + metrics.UploadSessionsCommitFailed.Inc() + // Keep the staged bytes: the blobstore outage may be transient, so an + // admin can retry with RestartPostprocessing rather than lose the upload. + c.rollbackNode(ctx, session, "commit failed: "+err.Error()) + metrics.UploadProcessing.Dec() + c.publishUploadFailed(ctx, session, ev) + } + return + case events.PPOutcomeAbort: + metrics.UploadSessionsAborted.Inc() + // Keep the staged bytes: an abort is a transient failure and the upload can + // be restarted with RestartPostprocessing. + c.rollbackNode(ctx, session, "postprocessing aborted") + case events.PPOutcomeDelete: + metrics.UploadSessionsDeleted.Inc() + c.rollbackPrepared(ctx, session, session.SizeDiff()) + default: + log.Error().Str("outcome", string(ev.Outcome)).Str("uploadid", ev.UploadID).Msg("unknown postprocessing outcome, aborting") + metrics.UploadSessionsAborted.Inc() + c.rollbackNode(ctx, session, "unknown postprocessing outcome: "+string(ev.Outcome)) + } + + c.publishUploadFailed(ctx, session, ev) +} + +// onRestartPostprocessing re-publishes BytesReceived so a previously aborted +// upload gets another postprocessing run. +func (c *coordinator) onRestartPostprocessing(ctx context.Context, ev events.RestartPostprocessing, log *zerolog.Logger) { + session, err := c.store.Get(ctx, ev.UploadID) + if err != nil { + log.Error().Err(err).Str("uploadid", ev.UploadID).Msg("RestartPostprocessing: could not load session") + return + } + metrics.UploadSessionsRestarted.Inc() + if err := c.publishBytesReceived(session.Context(ctx), session); err != nil { + log.Error().Err(err).Str("uploadid", ev.UploadID).Msg("could not restart postprocessing") + } +} + +// rollbackNode reverts the node to its pre-upload state but keeps the staged +// bytes and the session, so postprocessing can be restarted. +func (c *coordinator) rollbackNode(ctx context.Context, session Session, reason string) { + ref := session.Reference() + if err := c.fs.RollbackUpload(ctx, &ref, session.ID(), rollbackInfo(session, session.SizeDiff())); err != nil { + appctx.GetLogger(ctx).Error().Err(err).Str("uploadid", session.ID()).Msg("could not roll back upload, keeping session") + return + } + c.unmarkProcessing(ctx, session, &ref) + + // the size was given back, so a later cleanup of the kept session must not + // release it again + session.SetSizeDiff(0) + session.SetStatus(SessionStatusFailed, reason) + if err := session.Persist(ctx); err != nil { + appctx.GetLogger(ctx).Error().Err(err).Str("uploadid", session.ID()).Msg("could not persist the rolled back session") + } +} + +// publishUploadFailed tells consumers the upload will not become available. +// Clients wait on UploadReady, so staying silent would leave them hanging. +func (c *coordinator) publishUploadFailed(ctx context.Context, session Session, ev events.PostprocessingFinished) { + if c.pub == nil { + return + } + if err := events.Publish(ctx, c.pub, events.UploadReady{ + UploadID: session.ID(), + Failed: true, + Filename: session.Filename(), + SpaceOwner: session.SpaceOwner(), + ExecutingUser: ev.ExecutingUser, + FileRef: c.uploadRef(session), + ResourceID: &provider.ResourceId{ + StorageId: session.ProviderID(), + SpaceId: session.SpaceID(), + OpaqueId: session.NodeID(), + }, + Timestamp: utils.TSNow(), + IsVersion: session.VersionCreated(), + ImpersonatingUser: ev.ImpersonatingUser, + }); err != nil { + appctx.GetLogger(ctx).Error().Err(err).Str("uploadid", session.ID()).Msg("failed to publish UploadReady event") + } +} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/upload/session.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/upload/session.go new file mode 100644 index 0000000000..8899d934d9 --- /dev/null +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/upload/session.go @@ -0,0 +1,529 @@ +package upload + +import ( + "context" + "crypto/md5" //nolint:gosec + "crypto/sha1" //nolint:gosec + "encoding/hex" + "encoding/json" + "fmt" + "hash" + "hash/adler32" + "io" + "os" + "path/filepath" + "strconv" + "strings" + "time" + + userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" + provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" + typespb "github.com/cs3org/go-cs3apis/cs3/types/v1beta1" + "github.com/golang-jwt/jwt/v5" + "github.com/google/renameio/v2" + "github.com/pkg/errors" + tusd "github.com/tus/tusd/v2/pkg/handler" + + "github.com/opencloud-eu/reva/v2/pkg/appctx" + ctxpkg "github.com/opencloud-eu/reva/v2/pkg/ctx" + "github.com/opencloud-eu/reva/v2/pkg/errtypes" + "github.com/opencloud-eu/reva/v2/pkg/storage" + "github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/disk" + "github.com/opencloud-eu/reva/v2/pkg/utils" +) + +const defaultFilePerm = os.FileMode(0664) + +// Session status values, stored in the session's "status" metadata +const ( + SessionStatusUploading = "uploading" + SessionStatusProcessing = "processing" + SessionStatusFailed = "failed" +) + +// FileSession is the Session implementation for disk-backed uploads. While an +// upload is in progress, incoming bytes are staged in a .bin file and upload +// metadata (size, owner, checksums, etc.) is persisted in a .info file. Both +// survive process restarts, allowing TUS resumption. +// +// In scope: read/write the staged .bin file, persist/load upload metadata in the .info file. +// Out of scope: TUS protocol, checksums, event publishing, postprocessing — those live in coordinatedUpload and coordinator. +type FileSession struct { + store *FileStore + info tusd.FileInfo +} + +// Session is the driver-agnostic view of an upload session the Coordinator +// needs. Implementations must be pure state (CRUD): protocol orchestration +// belongs to coordinatedUpload or the coordinator itself. +type Session interface { + storage.UploadSession + + // Data access — delegated to by coordinatedUpload for TUS reads/writes. + GetInfo(ctx context.Context) (tusd.FileInfo, error) + GetReader(ctx context.Context) (io.ReadCloser, error) + WriteChunk(ctx context.Context, offset int64, src io.Reader) (int64, error) + + // Internal coordinator plumbing. + Chunk() string + BinPath() string + ExecutantUser() *userpb.User + ProviderID() string + SpaceID() string + NodeID() string + NodeParentID() string + NodeExists() bool + Dir() string + URL(ctx context.Context) (string, error) + SetScanData(result string, date time.Time) + SetStatus(status, msg string) + Checksums() storage.UploadChecksums + SetChecksums(sha1, md5, adler32 []byte) + SizeDiff() int64 + SetSizeDiff(d int64) + VersionCreated() bool + SetVersionCreated(v bool) + Metadata() map[string]string + Persist(ctx context.Context) error + Cleanup(ctx context.Context, cleanBin, cleanInfo bool) + Context(ctx context.Context) context.Context + + // Typed setters used by Coordinator.InitiateUpload to populate a new session + // without knowing internal storage key names. + SetStorageValue(key, value string) + SetMetadata(key, value string) + SetSize(size int64) + SetSizeIsDeferred(value bool) + SetExecutant(u *userpb.User) + TouchBin() error +} + +func (s *FileSession) GetInfo(_ context.Context) (tusd.FileInfo, error) { + return s.info, nil +} + +func (s *FileSession) GetReader(_ context.Context) (io.ReadCloser, error) { + return os.Open(s.binPath()) +} + +func (s *FileSession) WriteChunk(ctx context.Context, offset int64, src io.Reader) (int64, error) { + log := appctx.GetLogger(ctx) + file, err := os.OpenFile(s.binPath(), os.O_WRONLY|os.O_APPEND, defaultFilePerm) + if err != nil { + log.Error().Err(err).Str("uploadid", s.info.ID).Msg("WriteChunk: error opening upload file") + return 0, err + } + defer func() { + // sync each chunk right away: the upload can be resumed after a crash, and slow + // disks are spared one large flush at the end of the upload + _ = disk.Fdatasync(file) + _ = file.Close() + }() + + n, err := io.Copy(file, src) + if err != nil && err != io.ErrUnexpectedEOF { + log.Error().Err(err).Str("uploadid", s.info.ID).Msg("WriteChunk: error copying data to upload file") + return n, err + } + s.info.Offset += n + return n, nil +} + +// Purge removes all on-disk state for this session. +func (s *FileSession) Purge(ctx context.Context) { + s.Cleanup(ctx, true, true) +} + +// ScanData returns the AV scan result and scan date stored on the session. +func (s *FileSession) ScanData() (string, time.Time) { + date := s.info.MetaData["scanDate"] + if date == "" { + return "", time.Time{} + } + d, _ := time.Parse(time.RFC3339, date) + return s.info.MetaData["scanResult"], d +} + +// ID returns the upload session ID. +func (s *FileSession) ID() string { + return s.info.ID +} + +// Filename returns the filename stored in the session. +func (s *FileSession) Filename() string { + return s.info.Storage["NodeName"] +} + +// Size returns the declared upload size. +func (s *FileSession) Size() int64 { + return s.info.Size +} + +// Offset returns the current upload offset. +func (s *FileSession) Offset() int64 { + return s.info.Offset +} + +// Chunk returns the chunk basename stored in the session, or "" for non-chunked uploads. +func (s *FileSession) Chunk() string { + return s.info.Storage["Chunk"] +} + +// BinPath returns the path to the staged binary file. +func (s *FileSession) BinPath() string { + return s.binPath() +} + +// SpaceGid returns the numeric GID of the space owner, or "" if not set. +func (s *FileSession) SpaceGid() string { + return s.info.Storage["SpaceGid"] +} + +// ProviderID returns the storage provider ID stored in the session. +func (s *FileSession) ProviderID() string { + return s.info.MetaData["providerID"] +} + +// SpaceID returns the space (root) ID. +func (s *FileSession) SpaceID() string { + return s.info.Storage["SpaceRoot"] +} + +// NodeID returns the node ID for this upload. +func (s *FileSession) NodeID() string { + return s.info.Storage["NodeId"] +} + +// NodeParentID returns the parent node ID for this upload. +func (s *FileSession) NodeParentID() string { + return s.info.Storage["NodeParentId"] +} + +// NodeExists returns whether the target node existed when the upload was initiated. +func (s *FileSession) NodeExists() bool { + return s.info.Storage["NodeExists"] == "true" +} + +// Dir returns the directory portion of the upload path. +func (s *FileSession) Dir() string { + return s.info.Storage["Dir"] +} + +// IsProcessing returns true if the upload is in the processing state, meaning that the upload has finished and postprocessing is still running. +func (s *FileSession) IsProcessing() bool { + return s.info.MetaData["status"] == SessionStatusProcessing +} + +// SetStatus sets the status of the upload session +func (s *FileSession) SetStatus(status, msg string) { + s.info.MetaData["status"] = status + s.info.MetaData["statusMessage"] = msg +} + +// Status returns the status of the upload session +func (s *FileSession) Status() string { + return s.info.MetaData["status"] +} + +// StatusMessage returns the status message of the upload session +func (s *FileSession) StatusMessage() string { + return s.info.MetaData["statusMessage"] +} + +// SpaceOwner returns the space owner user ID. +func (s *FileSession) SpaceOwner() *userpb.UserId { + return &userpb.UserId{ + OpaqueId: s.info.Storage["SpaceOwnerOrManager"], + Idp: s.info.Storage["SpaceOwnerIdp"], + Type: userpb.UserType(userpb.UserType_value[s.info.Storage["SpaceOwnerType"]]), + } +} + +// Executant returns the user ID of the user who initiated this upload. +func (s *FileSession) Executant() userpb.UserId { + return userpb.UserId{ + Type: utils.UserTypeMap(s.info.Storage["UserType"]), + Idp: s.info.Storage["Idp"], + OpaqueId: s.info.Storage["UserId"], + } +} + +// Expires returns the upload expiry time. +func (s *FileSession) Expires() time.Time { + var t time.Time + if value, ok := s.info.MetaData["expires"]; ok { + t, _ = utils.MTimeToTime(value) + } + return t +} + +// Reference returns a CS3 reference for the resource being uploaded. +func (s *FileSession) Reference() provider.Reference { + return provider.Reference{ + ResourceId: &provider.ResourceId{ + StorageId: s.info.MetaData["providerID"], + SpaceId: s.info.Storage["SpaceRoot"], + OpaqueId: s.info.Storage["NodeId"], + }, + } +} + +// Checksums returns the pre-computed checksums stored on the session. +func (s *FileSession) Checksums() storage.UploadChecksums { + decode := func(key string) []byte { + b, _ := hex.DecodeString(s.info.MetaData[key]) + return b + } + return storage.UploadChecksums{ + SHA1: decode("checksumSHA1"), + MD5: decode("checksumMD5"), + Adler32: decode("checksumAdler32"), + } +} + +// Metadata returns the upload metadata the coordinator passes to the driver. +func (s *FileSession) Metadata() map[string]string { + return map[string]string{ + "providerID": s.info.MetaData["providerID"], + "mtime": s.info.MetaData["mtime"], + "nodeExists": s.info.Storage["NodeExists"], + "sessionID": s.info.ID, + "if-match": s.info.MetaData["if-match"], + "if-none-match": s.info.MetaData["if-none-match"], + "if-unmodified-since": s.info.MetaData["if-unmodified-since"], + } +} + +// SizeDiff returns the tree size change PrepareUpload propagated optimistically. +// Rolling an upload back has to undo exactly that amount. +func (s *FileSession) SizeDiff() int64 { + d, _ := strconv.ParseInt(s.info.MetaData["sizeDiff"], 10, 64) + return d +} + +// SetSizeDiff records the size change PrepareUpload reported. It is persisted +// because the async path prepares and commits in different processes, so the +// value cannot be held in memory between the two. +func (s *FileSession) SetSizeDiff(d int64) { + s.info.MetaData["sizeDiff"] = strconv.FormatInt(d, 10) +} + +// VersionCreated reports whether this upload superseded existing content, which +// UploadReady consumers use to tell an overwrite from a new file. +func (s *FileSession) VersionCreated() bool { + return s.info.MetaData["versionCreated"] == "true" +} + +// SetVersionCreated records what PrepareUpload reported. Persisted for the same +// reason as the size diff: on the async path the commit runs in another process. +func (s *FileSession) SetVersionCreated(v bool) { + s.info.MetaData["versionCreated"] = strconv.FormatBool(v) +} + +// SetScanData stores AV scan results on the session. +func (s *FileSession) SetScanData(result string, date time.Time) { + s.info.MetaData["scanResult"] = result + s.info.MetaData["scanDate"] = date.Format(time.RFC3339) +} + +// SetChecksums stores pre-computed checksums so CommitUpload can use them without +// re-reading the binary file. +func (s *FileSession) SetChecksums(sha1Sum, md5Sum, adler32Sum []byte) { + s.info.MetaData["checksumSHA1"] = hex.EncodeToString(sha1Sum) + s.info.MetaData["checksumMD5"] = hex.EncodeToString(md5Sum) + s.info.MetaData["checksumAdler32"] = hex.EncodeToString(adler32Sum) +} + +// SetMetadata sets a user-visible upload metadata field. +func (s *FileSession) SetMetadata(key, value string) { + s.info.MetaData[key] = value +} + +// SetStorageValue sets an internal storage field on the session. +func (s *FileSession) SetStorageValue(key, value string) { + s.info.Storage[key] = value +} + +// SetSize updates the declared upload size. +func (s *FileSession) SetSize(size int64) { + s.info.Size = size +} + +// SetSizeIsDeferred marks the upload size as not yet known. +func (s *FileSession) SetSizeIsDeferred(value bool) { + s.info.SizeIsDeferred = value +} + +// SetExecutant stores the identity of the user who initiated the upload. +func (s *FileSession) SetExecutant(u *userpb.User) { + s.info.Storage["Idp"] = u.GetId().GetIdp() + s.info.Storage["UserId"] = u.GetId().GetOpaqueId() + s.info.Storage["UserType"] = utils.UserTypeToString(u.GetId().Type) + s.info.Storage["UserName"] = u.GetUsername() + s.info.Storage["UserDisplayName"] = u.GetDisplayName() + b, _ := json.Marshal(u.GetOpaque()) + s.info.Storage["UserOpaque"] = string(b) + g, _ := json.Marshal(u.GetGroups()) + s.info.Storage["UserGroups"] = string(g) +} + +// TouchBin creates the empty staging file. +func (s *FileSession) TouchBin() error { + f, err := os.OpenFile(s.binPath(), os.O_CREATE|os.O_WRONLY, defaultFilePerm) + if err != nil { + return err + } + return f.Close() +} + +// Persist writes the session metadata atomically to disk. +func (s *FileSession) Persist(ctx context.Context) error { + infoPath := s.infoPath() + if err := os.MkdirAll(filepath.Dir(infoPath), 0700); err != nil { + return err + } + d, err := json.Marshal(s.info) + if err != nil { + return err + } + return renameio.WriteFile(infoPath, d, 0600) +} + +// Cleanup removes the staged binary and/or info file. +// Node deletion and processing flag changes are the coordinator's responsibility. +func (s *FileSession) Cleanup(ctx context.Context, cleanBin, cleanInfo bool) { + if cleanBin { + if err := os.Remove(s.binPath()); err != nil && !errors.Is(err, os.ErrNotExist) { + appctx.GetLogger(ctx).Error().Str("path", s.binPath()).Err(err).Msg("filestore: removing staged binary failed") + } + } + if cleanInfo { + if err := os.Remove(s.infoPath()); err != nil && !errors.Is(err, os.ErrNotExist) { + appctx.GetLogger(ctx).Error().Str("path", s.infoPath()).Err(err).Msg("filestore: removing session info failed") + } + } +} + +// Context reconstructs a context carrying the user, logger, lock ID, and +// initiator ID that were recorded when the upload was initiated. +func (s *FileSession) Context(ctx context.Context) context.Context { + sub := s.store.log.With().Int("pid", os.Getpid()).Logger() + ctx = appctx.WithLogger(ctx, &sub) + ctx = ctxpkg.ContextSetLockID(ctx, s.info.MetaData["lockid"]) + ctx = ctxpkg.ContextSetUser(ctx, s.ExecutantUser()) + return ctxpkg.ContextSetInitiator(ctx, s.info.MetaData["initiatorid"]) +} + +// URL returns the URL that the postprocessing service can use to download the +// staged binary: a signed JWT URL via the data gateway, or the data server's own +// URL when no data gateway is configured, because the proxy signs data URLs at +// the edge. +func (s *FileSession) URL(_ context.Context) (string, error) { + type transferClaims struct { + jwt.RegisteredClaims + Target string `json:"target"` + } + + target := joinURLParts(s.store.opts.DownloadEndpoint, "tus/", s.info.ID) + if s.store.opts.DataGatewayEndpoint == "" { + return target, nil + } + ttl := time.Duration(s.store.opts.TransferExpires) * time.Second + claims := transferClaims{ + RegisteredClaims: jwt.RegisteredClaims{ + ExpiresAt: jwt.NewNumericDate(time.Now().Add(ttl)), + Audience: jwt.ClaimStrings{"reva"}, + IssuedAt: jwt.NewNumericDate(time.Now()), + }, + Target: target, + } + t := jwt.NewWithClaims(jwt.GetSigningMethod("HS256"), claims) + tkn, err := t.SignedString([]byte(s.store.opts.TransferSharedSecret)) + if err != nil { + return "", errors.Wrapf(err, "filestore: error signing transfer token with claims %+v", claims) + } + return joinURLParts(s.store.opts.DataGatewayEndpoint, tkn), nil +} + +func (s *FileSession) ToFileInfo() tusd.FileInfo { + return s.info +} + +func (s *FileSession) InitiatorID() string { + return s.info.MetaData["initiatorid"] +} + +func (s *FileSession) binPath() string { + return filepath.Join(s.store.uploadDir, s.info.ID) +} + +func (s *FileSession) infoPath() string { + return fileSessionPath(s.store.uploadDir, s.info.ID) +} + +// ExecutantUser returns the full identity of the user who initiated the upload. +// Upload events must carry it rather than the bare id from Executant(): consumers +// read the display name straight off the event and do not look it up, so an +// id-only user reaches the activity feed with a blank name. +func (s *FileSession) ExecutantUser() *userpb.User { + var o *typespb.Opaque + _ = json.Unmarshal([]byte(s.info.Storage["UserOpaque"]), &o) + var groups []string + _ = json.Unmarshal([]byte(s.info.Storage["UserGroups"]), &groups) + return &userpb.User{ + Id: &userpb.UserId{ + Type: utils.UserTypeMap(s.info.Storage["UserType"]), + Idp: s.info.Storage["Idp"], + OpaqueId: s.info.Storage["UserId"], + }, + Username: s.info.Storage["UserName"], + DisplayName: s.info.Storage["UserDisplayName"], + Opaque: o, + Groups: groups, + } +} + +// fileSessionPath returns the path to the .info file for the given session ID. +func fileSessionPath(uploadDir, id string) string { + return filepath.Join(uploadDir, id+".info") +} + +// calculateChecksums computes sha1, md5, and adler32 in a single pass over path. +func calculateChecksums(_ context.Context, path string) (hash.Hash, hash.Hash, hash.Hash32, error) { + sha1h := sha1.New() //nolint:gosec + md5h := md5.New() //nolint:gosec + adler32h := adler32.New() + + f, err := os.Open(path) + if err != nil { + return nil, nil, nil, err + } + defer f.Close() + + r1 := io.TeeReader(f, sha1h) + r2 := io.TeeReader(r1, md5h) + if _, err = io.Copy(adler32h, r2); err != nil { + return nil, nil, nil, err + } + return sha1h, md5h, adler32h, nil +} + +func checkHash(expected string, h hash.Hash) error { + got := hex.EncodeToString(h.Sum(nil)) + if expected != got { + return errtypes.ChecksumMismatch(fmt.Sprintf("invalid checksum: expected %s got %s", expected, got)) + } + return nil +} + +// joinURLParts concatenates URL path segments, inserting "/" between them if needed. +func joinURLParts(parts ...string) string { + var b strings.Builder + for i, p := range parts { + b.WriteString(p) + if i < len(parts)-1 && !strings.HasSuffix(p, "/") { + b.WriteByte('/') + } + } + return b.String() +} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/upload/tus_adapter.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/upload/tus_adapter.go new file mode 100644 index 0000000000..52c44e689c --- /dev/null +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/upload/tus_adapter.go @@ -0,0 +1,175 @@ +package upload + +import ( + "context" + "fmt" + "io" + "net/http" + "os" + "time" + + tusd "github.com/tus/tusd/v2/pkg/handler" + + "github.com/opencloud-eu/reva/v2/pkg/appctx" + "github.com/opencloud-eu/reva/v2/pkg/errtypes" +) + +var errNotImplemented = tusd.NewError("ERR_NOT_IMPLEMENTED", "use InitiateUpload on the CS3 API to start a new upload", http.StatusNotImplemented) + +// tusAdapter adapts a single upload session to tusd's Upload interfaces. +type tusAdapter struct { + session Session + coord *coordinator +} + +func (u *tusAdapter) GetInfo(ctx context.Context) (tusd.FileInfo, error) { + return u.session.GetInfo(ctx) +} + +func (u *tusAdapter) GetReader(ctx context.Context) (io.ReadCloser, error) { + return u.session.GetReader(ctx) +} + +// ServeContent serves the staged bytes, honouring a Range header: postprocessing reads +// only the first bytes of a file larger than it scans. +func (u *tusAdapter) ServeContent(_ context.Context, w http.ResponseWriter, r *http.Request) error { + f, err := os.Open(u.session.BinPath()) + if err != nil { + return err + } + defer f.Close() + http.ServeContent(w, r, "", time.Time{}, f) + return nil +} + +func (u *tusAdapter) WriteChunk(ctx context.Context, offset int64, src io.Reader) (int64, error) { + return u.session.WriteChunk(ctx, offset, src) +} + +// FinishUpload runs the coordinator's finish path once all bytes have arrived. +func (u *tusAdapter) FinishUpload(ctx context.Context) error { + _, err := u.coord.finishUpload(u.session.Context(ctx), u.session) + if err != nil { + // tusd only answers the client, so log the cause here + appctx.GetLogger(ctx).Error().Err(err).Str("uploadid", u.session.ID()).Msg("failed to finish upload") + } + + // tusd answers an error type it does not recognise with a bare 500. + switch err.(type) { + case nil: + return nil + case errtypes.AlreadyExists: + return tusd.NewError("ERR_ALREADY_EXISTS", err.Error(), http.StatusConflict) + case errtypes.ResourceProcessing, errtypes.TooEarly: + return tusd.NewError("ERR_TOO_EARLY", err.Error(), http.StatusTooEarly) + case errtypes.Aborted: + return tusd.NewError("ERR_PRECONDITION_FAILED", err.Error(), http.StatusPreconditionFailed) + case errtypes.PreconditionFailed: + return tusd.NewError("ERR_PRECONDITION_FAILED", err.Error(), http.StatusMethodNotAllowed) + case errtypes.Locked: + return tusd.NewError("ERR_LOCKED", err.Error(), http.StatusLocked) + case errtypes.BadRequest: + return tusd.NewError("ERR_BAD_REQUEST", err.Error(), http.StatusBadRequest) + case errtypes.ChecksumMismatch: + return tusd.NewError("ERR_CHECKSUM_MISMATCH", err.Error(), errtypes.StatusChecksumMismatch) + case errtypes.IsPermissionDenied: + return tusd.NewError("ERR_PERMISSION_DENIED", err.Error(), http.StatusForbidden) + case errtypes.InsufficientStorage: + return tusd.NewError("ERR_INSUFFICIENT_STORAGE", err.Error(), http.StatusInsufficientStorage) + default: + return err + } +} + +// Terminate discards an upload, so a cancelled one leaves nothing behind. +func (u *tusAdapter) Terminate(ctx context.Context) error { + ref := u.session.Reference() + + // Rollback rather than Delete, which is permission-gated. It is a no-op unless + // this upload still owns the node. + if err := u.coord.fs.RollbackUpload(ctx, &ref, u.session.ID(), rollbackInfo(u.session, u.session.SizeDiff())); err != nil { + appctx.GetLogger(ctx).Error().Err(err).Str("uploadid", u.session.ID()).Msg("could not roll back terminated upload, keeping session") + return err + } + // A node that was never created cannot be unmarked, which is the normal case here. + if err := u.coord.fs.MarkProcessing(ctx, &ref, false, u.session.ID()); err != nil { + appctx.GetLogger(ctx).Debug().Err(err).Str("uploadid", u.session.ID()).Msg("could not unmark terminated upload") + } + + u.session.Cleanup(ctx, true, true) + return nil +} + +// DeclareLength records the total size for uploads initiated without one. +func (u *tusAdapter) DeclareLength(ctx context.Context, length int64) error { + u.session.SetSize(length) + u.session.SetSizeIsDeferred(false) + return u.session.Persist(ctx) +} + +// ConcatUploads appends the staged bytes of the partial uploads, in the order given. +func (u *tusAdapter) ConcatUploads(ctx context.Context, partials []tusd.Upload) error { + file, err := os.OpenFile(u.session.BinPath(), os.O_WRONLY|os.O_APPEND, defaultFilePerm) + if err != nil { + return err + } + defer file.Close() + + for _, partial := range partials { + p, ok := partial.(*tusAdapter) + if !ok { + return fmt.Errorf("coordinator: unexpected partial upload type %T", partial) + } + src, err := p.session.GetReader(ctx) + if err != nil { + return err + } + _, copyErr := io.Copy(file, src) + src.Close() + if copyErr != nil { + return copyErr + } + } + return nil +} + +// UseIn registers the coordinator as tusd's data store, in place of the driver's own. +func (c *coordinator) UseIn(composer *tusd.StoreComposer) { + composer.UseCore(c) + composer.UseTerminater(c) + composer.UseConcater(c) + composer.UseLengthDeferrer(c) + composer.UseContentServer(c) +} + +// NewUpload is unsupported: uploads always start through the CS3 InitiateUpload call. +func (c *coordinator) NewUpload(_ context.Context, _ tusd.FileInfo) (tusd.Upload, error) { + return nil, errNotImplemented +} + +// GetUpload wraps the session with the given id for the TUS data path. +func (c *coordinator) GetUpload(ctx context.Context, id string) (tusd.Upload, error) { + session, err := c.store.Get(ctx, id) + if err != nil { + return nil, err + } + return &tusAdapter{session: session, coord: c}, nil +} + +// The As* methods let tusd reach the extension interfaces on a plain tusd.Upload. + +func (c *coordinator) AsTerminatableUpload(up tusd.Upload) tusd.TerminatableUpload { + return up.(*tusAdapter) +} + +func (c *coordinator) AsLengthDeclarableUpload(up tusd.Upload) tusd.LengthDeclarableUpload { + return up.(*tusAdapter) +} + +func (c *coordinator) AsConcatableUpload(up tusd.Upload) tusd.ConcatableUpload { + return up.(*tusAdapter) +} + +func (c *coordinator) AsServableUpload(up tusd.Upload) tusd.ServableUpload { + return up.(*tusAdapter) +} diff --git a/vendor/modules.txt b/vendor/modules.txt index 6127049317..b37bf127a9 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -1357,7 +1357,7 @@ github.com/opencloud-eu/icap-client # github.com/opencloud-eu/libre-graph-api-go v1.0.9-0.20261016073229-17ed3d5dd346 ## explicit; go 1.23 github.com/opencloud-eu/libre-graph-api-go -# github.com/opencloud-eu/reva/v2 v2.52.2 +# github.com/opencloud-eu/reva/v2 v2.52.3-0.20261113144838-03685668969d ## explicit; go 1.26.0 github.com/opencloud-eu/reva/v2/cmd/revad/internal/grace github.com/opencloud-eu/reva/v2/cmd/revad/runtime @@ -1648,7 +1648,6 @@ github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/timemanager github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/trashbin github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/tree github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/tree/propagator -github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/upload github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/usermapper github.com/opencloud-eu/reva/v2/pkg/storage/registry/loader github.com/opencloud-eu/reva/v2/pkg/storage/registry/registry @@ -1684,6 +1683,7 @@ github.com/opencloud-eu/reva/v2/pkg/token/manager/jwt github.com/opencloud-eu/reva/v2/pkg/token/manager/loader github.com/opencloud-eu/reva/v2/pkg/token/manager/registry github.com/opencloud-eu/reva/v2/pkg/trace +github.com/opencloud-eu/reva/v2/pkg/upload github.com/opencloud-eu/reva/v2/pkg/user github.com/opencloud-eu/reva/v2/pkg/user/manager/demo github.com/opencloud-eu/reva/v2/pkg/user/manager/json