diff --git a/services/graph/pkg/service/v0/api_driveitem_permissions.go b/services/graph/pkg/service/v0/api_driveitem_permissions.go index 15b53ad7b1..c0a3164a67 100644 --- a/services/graph/pkg/service/v0/api_driveitem_permissions.go +++ b/services/graph/pkg/service/v0/api_driveitem_permissions.go @@ -51,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 @@ -134,8 +156,8 @@ func logLevelForError(err error) zerolog.Level { return zerolog.ErrorLevel } -// errorCodeForError returns the graph error code err is rendered with. Unlike the error -// message, which may contain backend-controlled text, the code is always safe to log. +// 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() @@ -144,26 +166,29 @@ func errorCodeForError(err error) string { } // errorEvent starts a log event for err at the level matching its cause. It carries the error -// code, callers add the error message only when it cannot contain backend-controlled text. +// 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("errorCode", errorCodeForError(err)) + 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. The code of -// otherErr is logged under otherKey. +// 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("errorCode", errorCodeForError(err)).Str(otherKey, errorCodeForError(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. The error message is not recorded, it may contain -// backend-controlled text. +// 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))) @@ -183,26 +208,26 @@ func setSpanErrorStatus(span trace.Span, err error) { // Invite invites a user to a drive item. func (s DriveItemPermissionsService) Invite(ctx context.Context, resourceId *storageprovider.ResourceId, invite libregraph.DriveItemInvite) (_ libregraph.Permission, err error) { - ctx, span := s.tp.Tracer("graph").Start(ctx, "Invite") + 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).Err(err).Str("itemID", storagespace.FormatResourceID(resourceId)).Msg("could not select next gateway client") + 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 { - errorEvent(&logger, err).Str("itemID", storagespace.FormatResourceID(resourceId)).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("itemID", storagespace.FormatResourceID(resourceId)).Msg("unsupported resource type") + logger.Debug().Err(err).Str(_logKeyItemID, storagespace.FormatResourceID(resourceId)).Msg("unsupported resource type") return libregraph.Permission{}, err } @@ -210,20 +235,20 @@ 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("itemID", storagespace.FormatResourceID(resourceId)).Str("roleID", roleID).Msg("unknown role") + 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 { - logger.Debug().Err(err).Str("itemID", storagespace.FormatResourceID(resourceId)).Str("roleID", roleID).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 { notApplicableErr := errorcode.New(errorcode.InvalidRequest, "role not applicable to this resource") - logger.Debug().Err(notApplicableErr).Str("itemID", storagespace.FormatResourceID(resourceId)).Str("roleID", roleID).Msg("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 } @@ -251,7 +276,7 @@ func (s DriveItemPermissionsService) Invite(ctx context.Context, resourceId *sto if email := driveRecipient.GetEmail(); email != "" { if s.config.Commons == nil || !s.config.Commons.EnableGuestLinks { mailErr := errorcode.New(errorcode.NotSupported, "sharing with mail recipients is not enabled") - logger.Debug().Err(mailErr).Str("itemID", storagespace.FormatResourceID(resourceId)).Msg("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) @@ -262,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 { - errorEvent(&logger, err).Str("itemID", storagespace.FormatResourceID(resourceId)).Str("recipientType", "mail").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() @@ -272,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 { - errorEvent(&logger, err).Str("itemID", storagespace.FormatResourceID(resourceId)).Str("recipientType", "mail").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 } @@ -282,10 +307,10 @@ 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 { - errorEvent(&logger, err).Str("itemID", storagespace.FormatResourceID(resourceId)).Str("recipientType", "group").Msg("recipient lookup failed") + 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()) } @@ -301,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 { - errorEvent(&logger, err).Str("itemID", storagespace.FormatResourceID(resourceId)).Str("recipientType", "group").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() @@ -313,12 +338,12 @@ func (s DriveItemPermissionsService) Invite(ctx context.Context, resourceId *sto user, err = s.identityCache.GetAcceptedCS3User(ctx, objectID) if err == nil && IsSpaceRoot(statResponse.GetInfo().GetId()) { federatedErr := errorcode.New(errorcode.InvalidRequest, "federated user can not become a space member") - logger.Debug().Err(federatedErr).Str("itemID", storagespace.FormatResourceID(resourceId)).Msg("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 { - errorEvent(&logger, err).Str("itemID", storagespace.FormatResourceID(resourceId)).Str("recipientType", "user").Msg("recipient lookup failed") + 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()) } @@ -335,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 { - errorEvent(&logger, err).Str("itemID", storagespace.FormatResourceID(resourceId)).Str("recipientType", "ocm").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 } @@ -345,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 { - errorEvent(&logger, err).Str("itemID", storagespace.FormatResourceID(resourceId)).Str("recipientType", "ocm").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() @@ -358,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 { - errorEvent(&logger, err).Str("itemID", storagespace.FormatResourceID(resourceId)).Str("recipientType", "user").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() @@ -386,7 +411,7 @@ 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 { - logger.Error().Str("errorCode", errorCodeForError(err)).Str("itemID", storagespace.FormatResourceID(resourceId)).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()) } @@ -478,26 +503,26 @@ 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, err error) { - ctx, span := s.tp.Tracer("graph").Start(ctx, "SpaceRootInvite") + 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).Err(err).Str("driveID", storagespace.FormatResourceID(driveID)).Msg("could not select next gateway client") + 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 { spaceErr := errorcode.FromUtilsStatusCodeError(err) - errorEvent(&logger, spaceErr).Str("driveID", storagespace.FormatResourceID(driveID)).Msg("could not get space") + errorEvent(&logger, spaceErr).Str(_logKeyDriveID, storagespace.FormatResourceID(driveID)).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("driveID", storagespace.FormatResourceID(driveID)).Msg("unsupported space type") + logger.Debug().Err(spaceTypeErr).Str(_logKeyDriveID, storagespace.FormatResourceID(driveID)).Str(_logKeySpaceType, space.GetSpaceType()).Msg("unsupported space type") return libregraph.Permission{}, spaceTypeErr } @@ -507,26 +532,26 @@ 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, err error) { - ctx, span := s.tp.Tracer("graph").Start(ctx, "ListPermissions") + 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).Err(err).Str("itemID", storagespace.FormatResourceID(itemID)).Msg("could not select next gateway client") + 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 { - errorEvent(&logger, err).Str("itemID", storagespace.FormatResourceID(itemID)).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("itemID", storagespace.FormatResourceID(itemID)).Msg("unsupported resource type") + logger.Debug().Err(err).Str(_logKeyItemID, storagespace.FormatResourceID(itemID)).Msg("unsupported resource type") return collectionOfPermissions, err } @@ -577,7 +602,7 @@ func (s DriveItemPermissionsService) ListPermissions(ctx context.Context, itemID share.ResourceIDFilter(itemID), }, driveItems) if err != nil { - errorEvent(&logger, err).Str("itemID", storagespace.FormatResourceID(itemID)).Msg("could not list shares") + errorEvent(&logger, err).Str(_logKeyItemID, storagespace.FormatResourceID(itemID)).Msg("could not list space root shares") return collectionOfPermissions, err } } else { @@ -586,7 +611,7 @@ func (s DriveItemPermissionsService) ListPermissions(ctx context.Context, itemID share.ResourceIDFilter(itemID), }, driveItems) if err != nil { - errorEvent(&logger, err).Str("itemID", storagespace.FormatResourceID(itemID)).Msg("could not list shares") + errorEvent(&logger, err).Str(_logKeyItemID, storagespace.FormatResourceID(itemID)).Msg("could not list user shares") return collectionOfPermissions, err } if s.config.IncludeOCMSharees { @@ -597,7 +622,7 @@ func (s DriveItemPermissionsService) ListPermissions(ctx context.Context, itemID }, }, driveItems) if err != nil { - errorEvent(&logger, err).Str("itemID", storagespace.FormatResourceID(itemID)).Msg("could not list shares") + errorEvent(&logger, err).Str(_logKeyItemID, storagespace.FormatResourceID(itemID)).Msg("could not list ocm shares") return collectionOfPermissions, err } } @@ -609,7 +634,7 @@ func (s DriveItemPermissionsService) ListPermissions(ctx context.Context, itemID publicshare.ResourceIDFilter(itemID), }, driveItems) if err != nil { - errorEvent(&logger, err).Str("itemID", storagespace.FormatResourceID(itemID)).Msg("could not list shares") + errorEvent(&logger, err).Str(_logKeyItemID, storagespace.FormatResourceID(itemID)).Msg("could not list public shares") return collectionOfPermissions, err } } @@ -630,28 +655,28 @@ 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, err error) { - ctx, span := s.tp.Tracer("graph").Start(ctx, "ListSpaceRootPermissions") + 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).Err(err).Str("driveID", storagespace.FormatResourceID(driveID)).Msg("could not select next gateway client") + 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 { spaceErr := errorcode.FromUtilsStatusCodeError(err) - errorEvent(&logger, spaceErr).Str("driveID", storagespace.FormatResourceID(driveID)).Msg("could not get space") + 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 { spaceTypeErr := errorcode.New(errorcode.InvalidRequest, "unsupported space type") - logger.Debug().Err(spaceTypeErr).Str("driveID", storagespace.FormatResourceID(driveID)).Msg("unsupported space type") + logger.Debug().Err(spaceTypeErr).Str(_logKeyDriveID, storagespace.FormatResourceID(driveID)).Str(_logKeySpaceType, space.GetSpaceType()).Msg("unsupported space type") return collectionOfPermissions, spaceTypeErr } @@ -661,7 +686,7 @@ 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) (err error) { - ctx, span := s.tp.Tracer("graph").Start(ctx, "DeletePermission") + ctx, span := s.tp.Tracer(_tracerName).Start(ctx, "DeletePermission") defer func() { endSpan(span, err) }() logger := s.logger.SubloggerWithRequestID(ctx) @@ -699,71 +724,73 @@ func (s DriveItemPermissionsService) DeletePermission(ctx context.Context, itemI switch { case err != nil: - fallbackErrorEvent(&logger, err, lookupErr, "lookupErrorCode").Str("itemID", storagespace.FormatResourceID(itemID)).Str("permissionID", permissionID).Msg("could not resolve permission") + 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("itemID", storagespace.FormatResourceID(itemID)).Str("permissionID", permissionID).Msg("permission not found") + 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("itemID", storagespace.FormatResourceID(itemID)).Str("permissionID", permissionID).Msg("could not resolve the shared resource of the permission") + 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) { - logger.Debug().Str("itemID", storagespace.FormatResourceID(itemID)).Str("permissionID", permissionID).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: if err := s.removeUserShare(ctx, permissionID); err != nil { - errorEvent(&logger, err).Str("itemID", storagespace.FormatResourceID(itemID)).Str("permissionID", permissionID).Msg("could not remove permission") + errorEvent(&logger, err).Str(_logKeyItemID, storagespace.FormatResourceID(itemID)).Str(_logKeyPermissionID, permissionID).Msg("could not remove permission") return err } return nil case Public: if err := s.removePublicShare(ctx, permissionID); err != nil { - errorEvent(&logger, err).Str("itemID", storagespace.FormatResourceID(itemID)).Str("permissionID", permissionID).Msg("could not remove permission") + errorEvent(&logger, err).Str(_logKeyItemID, storagespace.FormatResourceID(itemID)).Str(_logKeyPermissionID, permissionID).Msg("could not remove permission") return err } return nil case OCM: if err := s.removeOCMPermission(ctx, permissionID); err != nil { - errorEvent(&logger, err).Str("itemID", storagespace.FormatResourceID(itemID)).Str("permissionID", permissionID).Msg("could not remove permission") + 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) (err error) { - ctx, span := s.tp.Tracer("graph").Start(ctx, "DeleteSpaceRootPermission") + 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).Err(err).Str("driveID", storagespace.FormatResourceID(driveID)).Str("permissionID", permissionID).Msg("could not select next gateway client") + 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 { spaceErr := errorcode.FromUtilsStatusCodeError(err) - errorEvent(&logger, spaceErr).Str("driveID", storagespace.FormatResourceID(driveID)).Str("permissionID", permissionID).Msg("could not get space") + errorEvent(&logger, spaceErr).Str(_logKeyDriveID, storagespace.FormatResourceID(driveID)).Str(_logKeyPermissionID, permissionID).Msg("could not get space") return spaceErr } if space.SpaceType != _spaceTypeProject { spaceTypeErr := errorcode.New(errorcode.InvalidRequest, "unsupported space type") - logger.Debug().Err(spaceTypeErr).Str("driveID", storagespace.FormatResourceID(driveID)).Str("permissionID", permissionID).Msg("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 } @@ -773,7 +800,7 @@ 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, err error) { - ctx, span := s.tp.Tracer("graph").Start(ctx, "UpdatePermission") + ctx, span := s.tp.Tracer(_tracerName).Start(ctx, "UpdatePermission") defer func() { endSpan(span, err) }() logger := s.logger.SubloggerWithRequestID(ctx) @@ -789,7 +816,7 @@ func (s DriveItemPermissionsService) UpdatePermission(ctx context.Context, itemI // if we still can't find the permission, return an error if err != nil { - fallbackErrorEvent(&logger, err, lookupErr, "lookupErrorCode").Str("itemID", storagespace.FormatResourceID(itemID)).Str("permissionID", permissionID).Msg("could not resolve permission") + 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 } @@ -797,7 +824,7 @@ func (s DriveItemPermissionsService) UpdatePermission(ctx context.Context, itemI // 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) { - logger.Debug().Str("itemID", storagespace.FormatResourceID(itemID)).Str("permissionID", permissionID).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") } @@ -805,7 +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("itemID", storagespace.FormatResourceID(itemID)).Str("permissionID", permissionID).Msg("could not update permission") + errorEvent(&logger, err).Str(_logKeyItemID, storagespace.FormatResourceID(itemID)).Str(_logKeyPermissionID, permissionID).Msg("could not update permission") return libregraph.Permission{}, err } return *updatedPermission, nil @@ -829,7 +856,7 @@ func (s DriveItemPermissionsService) UpdatePermission(ctx context.Context, itemI 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, "ocmErrorCode").Str("itemID", storagespace.FormatResourceID(itemID)).Str("permissionID", permissionID).Msg("could not update permission") + 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 @@ -838,26 +865,26 @@ func (s DriveItemPermissionsService) UpdatePermission(ctx context.Context, itemI // 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, err error) { - ctx, span := s.tp.Tracer("graph").Start(ctx, "UpdateSpaceRootPermission") + 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).Err(err).Str("driveID", storagespace.FormatResourceID(driveID)).Str("permissionID", permissionID).Msg("could not select next gateway client") + 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("driveID", storagespace.FormatResourceID(driveID)).Str("permissionID", permissionID).Msg("could not get space") + 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("driveID", storagespace.FormatResourceID(driveID)).Str("permissionID", permissionID).Msg("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 } 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 40eed7108d..aaf664239a 100644 --- a/services/graph/pkg/service/v0/api_driveitem_permissions_links.go +++ b/services/graph/pkg/service/v0/api_driveitem_permissions_links.go @@ -231,7 +231,7 @@ 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("itemID", storagespace.FormatResourceID(itemID)).Str("permissionID", permissionID).Msg("could not set link password") + errorEvent(&logger, err).Str(_logKeyItemID, storagespace.FormatResourceID(itemID)).Str(_logKeyPermissionID, permissionID).Msg("could not set link password") errorcode.RenderError(w, r, err) return } @@ -267,7 +267,7 @@ func (api DriveItemPermissionsApi) SetSpaceRootLinkPassword(w http.ResponseWrite newPermission, err := api.driveItemPermissionsService.SetPublicLinkPasswordOnSpaceRoot(ctx, &driveID, permissionID, password.GetPassword()) if err != nil { logger := api.logger.SubloggerWithRequestID(ctx) - errorEvent(&logger, err).Str("driveID", storagespace.FormatResourceID(&driveID)).Str("permissionID", permissionID).Msg("could not set link password") + errorEvent(&logger, err).Str(_logKeyDriveID, storagespace.FormatResourceID(&driveID)).Str(_logKeyPermissionID, permissionID).Msg("could not set link password") errorcode.RenderError(w, r, err) return } @@ -279,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.Debug().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_test.go b/services/graph/pkg/service/v0/api_driveitem_permissions_test.go index 2c4a6a03aa..c5bce19f34 100644 --- a/services/graph/pkg/service/v0/api_driveitem_permissions_test.go +++ b/services/graph/pkg/service/v0/api_driveitem_permissions_test.go @@ -109,6 +109,15 @@ func endedSpan(sr *tracetest.SpanRecorder, name string, sentinels ...string) sdk 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 @@ -185,11 +194,10 @@ var _ = Describe("DriveItemPermissionsService", func() { return service, logBuf } - // A failing gateway selection is an unexpected failure of every operation. Where the operation selects - // the gateway itself, the locally produced error message is logged. Where a probing helper selects it, - // only the error code is, like for every error that passed through a helper. + // 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) { + 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) @@ -200,9 +208,30 @@ var _ = Describe("DriveItemPermissionsService", func() { 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) - errorEntries := entriesAtLevel(entries, "error") - Expect(errorEntries).To(HaveLen(1)) + // 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"), @@ -211,7 +240,7 @@ var _ = Describe("DriveItemPermissionsService", func() { for k, v := range ids { expected = append(expected, HaveKeyWithValue(k, v)) } - Expect(errorEntries[0]).To(SatisfyAll(expected...)) + 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))) @@ -227,33 +256,33 @@ var _ = Describe("DriveItemPermissionsService", func() { 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")), + }, 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")), + }, 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")), + }, 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")), + }, 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"}, Not(HaveKey("error"))), + }, 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")), + }, 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"}, Not(HaveKey("error"))), + }, 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")), + }, 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() { @@ -286,7 +315,7 @@ var _ = Describe("DriveItemPermissionsService", func() { _, err := s.ListPermissions(ctx, driveItemId, svc.ListPermissionsQueryOptions{}) return err } - DescribeTable("logs stat failures by cause with the item id, without the backend message or the stat payload", + 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 "/" @@ -321,12 +350,14 @@ var _ = Describe("DriveItemPermissionsService", func() { Expect(entry).To(Equal(itemEntries[0])) } } - for _, payloadKey := range []string{"error", "stat.res", "res", "response", "request", "info", "Body", "body"} { + // 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))) } - // neither the backend message nor the stat payload reaches the log + // the stat payload never reaches the log raw := rawLog(entries) - for _, sentinel := range []string{"private-financial-report-2026.xlsx", "/private/project-plan.odt", "permission_set"} { + for _, sentinel := range []string{"/private/project-plan.odt", "permission_set"} { Expect(raw).ToNot(ContainSubstring(sentinel)) } }, @@ -355,7 +386,11 @@ var _ = Describe("DriveItemPermissionsService", func() { Expect(c.Method).To(Equal("ListStorageSpaces")) } - expected := []gomegatypes.GomegaMatcher{HaveKeyWithValue("level", "debug")} + 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)) @@ -425,11 +460,11 @@ var _ = Describe("DriveItemPermissionsService", func() { } 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()), - // the backend status message is not logged - Not(HaveKey("error")), + HaveKeyWithValue("error", expectedErr.Error()), } for _, k := range []string{"driveID", "permissionID", "itemID"} { if v, ok := ids[k]; ok { @@ -443,9 +478,6 @@ var _ = Describe("DriveItemPermissionsService", func() { for _, payloadKey := range []string{"space", "spaces", "res", "response", "stat.res"} { Expect(entries).ToNot(ContainElement(HaveKey(payloadKey))) } - raw, err := json.Marshal(entries) - Expect(err).ToNot(HaveOccurred()) - Expect(string(raw)).ToNot(ContainSubstring("Project Alpha")) if level == "debug" { Expect(entries).ToNot(ContainElement(HaveKeyWithValue("level", BeElementOf("error", "warn")))) } else { @@ -611,10 +643,8 @@ var _ = Describe("DriveItemPermissionsService", func() { HaveKeyWithValue("itemID", storagespace.FormatResourceID(driveItemId)), HaveKeyWithValue("recipientType", "mail"), HaveKeyWithValue("errorCode", "generalException"), - Not(HaveKey("error")), + HaveKeyWithValue("error", err.Error()), )) - // neither the backend text nor the recipient address reaches the log - Expect(rawLog(entries)).ToNot(ContainSubstring("guest@example.com")) }) It("rejects guest shares when guest invites are disabled by default", func() { @@ -683,11 +713,6 @@ var _ = Describe("DriveItemPermissionsService", func() { for _, payloadKey := range []string{"invite", "recipient", "recipients", "email", "mail", "Body", "body"} { Expect(entries).ToNot(ContainElement(HaveKey(payloadKey))) } - // recipient mail addresses and federated identifiers are never logged - raw, err := json.Marshal(entries) - Expect(err).ToNot(HaveOccurred()) - Expect(string(raw)).ToNot(ContainSubstring("guest@example.com")) - Expect(string(raw)).ToNot(ContainSubstring("remote@ocm.example.org")) }, Entry("unsupported resource type", func() *provider.ResourceId { @@ -786,24 +811,21 @@ var _ = Describe("DriveItemPermissionsService", func() { 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 { - errorEntries := entriesAtLevel(entries, "error") - Expect(errorEntries).To(HaveLen(1)) + 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))) } - // the recipient id never reaches the log, not even inside backend error messages - raw, err := json.Marshal(entries) - Expect(err).ToNot(HaveOccurred()) - Expect(string(raw)).ToNot(ContainSubstring("recipient-id-42")) }, Entry("A: group not found", "group", func() { @@ -854,6 +876,8 @@ var _ = Describe("DriveItemPermissionsService", func() { } } 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 { @@ -862,11 +886,6 @@ var _ = Describe("DriveItemPermissionsService", func() { for _, payloadKey := range []string{"objectID", "groupId", "userId", "email", "mail", "recipient", "recipients", "share", "invite", "Body", "body"} { Expect(entries).ToNot(ContainElement(HaveKey(payloadKey))) } - // recipient identifiers never reach the log, not even inside backend error messages - raw, err := json.Marshal(entries) - Expect(err).ToNot(HaveOccurred()) - Expect(string(raw)).ToNot(ContainSubstring("guest@example.com")) - Expect(string(raw)).ToNot(ContainSubstring("recipient-id-42")) }, Entry("A: mail recipient, internal error", "mail", func() { @@ -946,6 +965,8 @@ var _ = Describe("DriveItemPermissionsService", func() { } } 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 { @@ -954,11 +975,6 @@ var _ = Describe("DriveItemPermissionsService", func() { for _, payloadKey := range []string{"objectID", "userId", "domain", "provider", "share", "recipient", "recipients", "invite", "Body", "body"} { Expect(entries).ToNot(ContainElement(HaveKey(payloadKey))) } - // neither the federated identifier nor the remote domain reaches the log, not even inside backend error messages - raw, err := json.Marshal(entries) - Expect(err).ToNot(HaveOccurred()) - Expect(string(raw)).ToNot(ContainSubstring("remote@ocm.example.org")) - Expect(string(raw)).ToNot(ContainSubstring("ocm.example.org")) }, Entry("A: provider info lookup, internal error", func() { @@ -1052,7 +1068,7 @@ var _ = Describe("DriveItemPermissionsService", func() { }, codes.Error, "generalException"), ) - It("logs a failed inviter identity lookup as error with the item id only", func() { + 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 ... @@ -1083,16 +1099,13 @@ var _ = Describe("DriveItemPermissionsService", func() { Expect(errorEntries).To(HaveLen(1)) Expect(errorEntries[0]).To(SatisfyAll( HaveKeyWithValue("itemID", storagespace.FormatResourceID(driveItemId)), - // the cause of the failed lookup, without its message + // 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{"error", "userId", "userID", "objectID", "user", "invite", "share", "Body", "body"} { + for _, payloadKey := range []string{"userId", "userID", "objectID", "user", "invite", "share", "Body", "body"} { Expect(entries).ToNot(ContainElement(HaveKey(payloadKey))) } - // neither backend error text nor identity data reaches the log - raw, err := json.Marshal(entries) - Expect(err).ToNot(HaveOccurred()) - Expect(string(raw)).ToNot(ContainSubstring("inviter@example.com")) }) It("fails with when trying to set a space role on a file", func() { @@ -1339,9 +1352,9 @@ var _ = Describe("DriveItemPermissionsService", func() { 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)), - // the message is omitted, the error code still classifies the failure - Not(HaveKey("error")), + HaveKeyWithValue("error", err.Error()), HaveKeyWithValue("errorCode", "generalException"), )) for _, payloadKey := range []string{"shares", "share", "res", "response", "stat.res"} { @@ -1356,7 +1369,7 @@ var _ = Describe("DriveItemPermissionsService", func() { }) }) } - DescribeTable("does not log identity backend text when a share grantee lookup fails", + 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, @@ -1386,15 +1399,13 @@ var _ = Describe("DriveItemPermissionsService", func() { entries := logEntries(logBuf) errorEntries := entriesAtLevel(entries, "error") Expect(errorEntries).To(HaveLen(1)) - Expect(errorEntries[0]).To(HaveKeyWithValue("itemID", storagespace.FormatResourceID(listedItemID))) + 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))) } - // neither the identity value nor the backend message reach the log - raw, err := json.Marshal(entries) - Expect(err).ToNot(HaveOccurred()) - Expect(string(raw)).ToNot(ContainSubstring("private-group-dn-42")) - Expect(string(raw)).ToNot(ContainSubstring("ldap search failed")) }, Entry("user share listing", func(groupGrantee *provider.Grantee) *provider.ResourceId { @@ -1490,17 +1501,16 @@ var _ = Describe("DriveItemPermissionsService", func() { 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"), - Not(HaveKey("error")), + HaveKeyWithValue("error", err.Error()), )) - // the backend status message is not logged at any level - Expect(rawLog(entries)).ToNot(ContainSubstring("salary-2026.ods")) 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 once as error with the item id", func() { + 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() @@ -1516,12 +1526,15 @@ var _ = Describe("DriveItemPermissionsService", func() { gatewayClient.AssertCalled(GinkgoT(), "ListShares", mock.Anything, mock.Anything) gatewayClient.AssertNotCalled(GinkgoT(), "ListPublicShares", mock.Anything, mock.Anything) - errorEntries := entriesAtLevel(logEntries(logBuf), "error") - Expect(errorEntries).To(HaveLen(1)) - Expect(errorEntries[0]).To(SatisfyAll( - HaveKeyWithValue("itemID", storagespace.FormatResourceID(itemID)), - HaveKeyWithValue("errorCode", "generalException"), - Not(HaveKey("error")), + // 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() { @@ -1544,14 +1557,15 @@ var _ = Describe("DriveItemPermissionsService", func() { 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)), - Not(HaveKey("error")), + 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 once as error with the item id", func() { + 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 @@ -1569,14 +1583,17 @@ var _ = Describe("DriveItemPermissionsService", func() { gatewayClient.AssertNotCalled(GinkgoT(), "ListOCMShares", mock.Anything, mock.Anything) gatewayClient.AssertNotCalled(GinkgoT(), "ListPublicShares", mock.Anything, mock.Anything) - errorEntries := entriesAtLevel(logEntries(logBuf), "error") - Expect(errorEntries).To(HaveLen(1)) - Expect(errorEntries[0]).To(SatisfyAll( - HaveKeyWithValue("itemID", storagespace.FormatResourceID(itemID)), - Not(HaveKey("error")), + // 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 once as error with the item id", func() { + 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() @@ -1589,11 +1606,17 @@ var _ = Describe("DriveItemPermissionsService", func() { Expect(err).To(MatchError(errorcode.New(errorcode.GeneralException, gatewayErr.Error()))) gatewayClient.AssertNotCalled(GinkgoT(), "ListShares", mock.Anything, mock.Anything) - errorEntries := entriesAtLevel(logEntries(logBuf), "error") - Expect(errorEntries).To(HaveLen(1)) - Expect(errorEntries[0]).To(HaveKeyWithValue("itemID", storagespace.FormatResourceID(itemID))) + // 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 once as error with the item id", func() { + 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 @@ -1610,11 +1633,14 @@ var _ = Describe("DriveItemPermissionsService", func() { gatewayClient.AssertNotCalled(GinkgoT(), "ListShares", mock.Anything, mock.Anything) gatewayClient.AssertNotCalled(GinkgoT(), "ListPublicShares", mock.Anything, mock.Anything) - errorEntries := entriesAtLevel(logEntries(logBuf), "error") - Expect(errorEntries).To(HaveLen(1)) - Expect(errorEntries[0]).To(SatisfyAll( - HaveKeyWithValue("itemID", storagespace.FormatResourceID(spaceRootID)), - Not(HaveKey("error")), + // 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() { @@ -2189,14 +2215,14 @@ var _ = Describe("DriveItemPermissionsService", func() { HaveKeyWithValue("itemID", storagespace.FormatResourceID(getShareResponse.Share.ResourceId)), HaveKeyWithValue("permissionID", "permissionid"), HaveKeyWithValue("errorCode", "generalException"), - Not(HaveKey("error")), + // the error text tells operators the reason + HaveKeyWithValue("error", err.Error()), )) - Expect(rawLog(entries)).ToNot(ContainSubstring("salary-2026.ods")) for _, payloadKey := range []string{"share", "res", "response", "request", "Body", "body"} { Expect(entries).ToNot(ContainElement(HaveKey(payloadKey))) } }) - It("does not log the backend message when resolving a permission fails", func() { + 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 @@ -2218,9 +2244,8 @@ var _ = Describe("DriveItemPermissionsService", func() { HaveKeyWithValue("itemID", storagespace.FormatResourceID(getShareResponse.Share.ResourceId)), HaveKeyWithValue("permissionID", "permissionid"), HaveKeyWithValue("errorCode", "generalException"), - Not(HaveKey("error")), + HaveKeyWithValue("error", err.Error()), )) - Expect(rawLog(entries)).ToNot(ContainSubstring("salary-2026.ods")) }) DescribeTable("logs permission removal failures by cause with the item and permission ids", func(setup func() string, expectedErr error, level string) { @@ -2235,16 +2260,14 @@ var _ = Describe("DriveItemPermissionsService", func() { 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()), - Not(HaveKey("error")), + HaveKeyWithValue("error", expectedErr.Error()), ))) - // the backend status message is not logged at any level - backendMsg := strings.TrimPrefix(expectedErr.Error(), graphErr.GetCode().String()+": ") - Expect(rawLog(entries)).ToNot(ContainSubstring(backendMsg)) errorEntries := entriesAtLevel(entries, "error") if level == "error" { Expect(errorEntries).To(HaveLen(1)) @@ -2335,11 +2358,12 @@ var _ = Describe("DriveItemPermissionsService", func() { HaveKeyWithValue("permissionID", "permissionid"), HaveKeyWithValue("errorCode", "itemNotFound"), HaveKeyWithValue("lookupErrorCode", "generalException"), - Not(HaveKey("error")), + // 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()), )) - Expect(rawLog(entries)).ToNot(ContainSubstring("salary-2026.ods")) - // like the log, the span reports the hidden infrastructure failure, by its code only + // 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")) @@ -2678,7 +2702,7 @@ var _ = Describe("DriveItemPermissionsService", func() { Expect(err).To(HaveOccurred()) Expect(res).To(BeZero()) }) - It("logs a gateway selection failure while listing space root shares once as error with the item and permission ids", func() { + 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 @@ -2698,18 +2722,20 @@ var _ = Describe("DriveItemPermissionsService", func() { } entries := logEntries(logBuf) - errorEntries := entriesAtLevel(entries, "error") - Expect(errorEntries).To(HaveLen(1)) - Expect(errorEntries[0]).To(SatisfyAll( - HaveKeyWithValue("itemID", storagespace.FormatResourceID(spaceRootID)), - HaveKeyWithValue("permissionID", "permissionid"), - Not(HaveKey("error")), + // 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("does not log identity backend text when resolving a user share grantee fails", func() { + 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" @@ -2744,18 +2770,14 @@ var _ = Describe("DriveItemPermissionsService", func() { 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))) } - // neither the identity value nor the backend message reach the log - raw, err := json.Marshal(entries) - Expect(err).ToNot(HaveOccurred()) - Expect(string(raw)).ToNot(ContainSubstring("private-group-dn-42")) - Expect(string(raw)).ToNot(ContainSubstring("ldap search failed")) }) - DescribeTable("logs public link update failures once as error with the item and permission ids", - func(setup func(), expectedErr error) { + 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() @@ -2771,15 +2793,25 @@ var _ = Describe("DriveItemPermissionsService", func() { } entries := logEntries(logBuf) - errorEntries := entriesAtLevel(entries, "error") - Expect(errorEntries).To(HaveLen(1)) - Expect(errorEntries[0]).To(SatisfyAll( + // 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"), - Not(HaveKey("error")), + HaveKeyWithValue("error", expectedErr.Error()), )) - // no raw backend error text in any error level entry - Expect(errorEntries).ToNot(ContainElement(HaveKey("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))) } @@ -2796,7 +2828,7 @@ var _ = Describe("DriveItemPermissionsService", func() { Status: status.NewInternal(ctx, "link manager unavailable"), }, nil) }, - errorcode.New(errorcode.GeneralException, "link manager unavailable").WithOrigin(errorcode.ErrorOriginCS3)), + 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 @@ -2805,9 +2837,9 @@ var _ = Describe("DriveItemPermissionsService", func() { 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")), + errorcode.New(errorcode.GeneralException, "no gateway available"), 1), ) - It("does not log the backend stat message when a public link update fails", func() { + 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; @@ -2837,12 +2869,9 @@ var _ = Describe("DriveItemPermissionsService", func() { } } 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")))) - // neither the file name nor the backend message reaches the log - raw, err := json.Marshal(entries) - Expect(err).ToNot(HaveOccurred()) - Expect(string(raw)).ToNot(ContainSubstring("private-financial-report-2026.xlsx")) - Expect(string(raw)).ToNot(ContainSubstring(statMessage)) }) It("logs a user share update failure once as error with the item and permission ids", func() { service, logBuf := newLoggedService() @@ -2870,8 +2899,7 @@ var _ = Describe("DriveItemPermissionsService", func() { HaveKeyWithValue("itemID", storagespace.FormatResourceID(driveItemId)), HaveKeyWithValue("permissionID", "permissionid"), HaveKeyWithValue("errorCode", "generalException"), - // the update error can carry identity backend text, its message is not logged - Not(HaveKey("error")), + HaveKeyWithValue("error", err.Error()), )) for _, payloadKey := range []string{"share", "shares", "res", "response", "request", "Body", "body"} { Expect(entries).ToNot(ContainElement(HaveKey(payloadKey))) @@ -2919,13 +2947,12 @@ var _ = Describe("DriveItemPermissionsService", func() { HaveKeyWithValue("permissionID", "permissionid"), HaveKeyWithValue("errorCode", "itemNotFound"), HaveKeyWithValue("ocmErrorCode", "generalException"), - Not(HaveKey("error")), + // 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()), )) - raw, err := json.Marshal(entries) - Expect(err).ToNot(HaveOccurred()) - Expect(string(raw)).ToNot(ContainSubstring("ocm share manager unavailable")) - // like the log, the span reports the failed ocm update, by its code only + // 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")) @@ -2964,7 +2991,7 @@ var _ = Describe("DriveItemPermissionsService", func() { Expect(span.Status().Code).To(Equal(codes.Unset)) Expect(span.Attributes()).To(ContainElement(attribute.String("error.type", "itemNotFound"))) }) - It("does not log identity backend text when converting the updated user share fails", func() { + 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 @@ -3003,11 +3030,8 @@ var _ = Describe("DriveItemPermissionsService", func() { HaveKeyWithValue("itemID", storagespace.FormatResourceID(driveItemId)), HaveKeyWithValue("permissionID", "permissionid"), HaveKeyWithValue("errorCode", "generalException"), + HaveKeyWithValue("error", err.Error()), )) - raw, err := json.Marshal(entries) - Expect(err).ToNot(HaveOccurred()) - Expect(string(raw)).ToNot(ContainSubstring("private-group-dn-42")) - Expect(string(raw)).ToNot(ContainSubstring("ldap search failed")) }) It("does not log a permission that is not found by any lookup as error", func() { service, logBuf := newLoggedService() @@ -3056,11 +3080,12 @@ var _ = Describe("DriveItemPermissionsService", func() { HaveKeyWithValue("permissionID", "permissionid"), HaveKeyWithValue("errorCode", "itemNotFound"), HaveKeyWithValue("lookupErrorCode", "generalException"), - Not(HaveKey("error")), + // 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()), )) - Expect(rawLog(entries)).ToNot(ContainSubstring("salary-2026.ods")) - // like the log, the span reports the hidden infrastructure failure, by its code only + // 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")) @@ -3532,9 +3557,11 @@ var _ = Describe("DriveItemPermissionsApi", func() { } } 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)) @@ -3544,21 +3571,21 @@ var _ = Describe("DriveItemPermissionsApi", func() { for _, payloadKey := range []string{"password", "Body", "body", "request", "response", "token", "Authorization"} { Expect(entries).ToNot(ContainElement(HaveKey(payloadKey))) } - // neither the password, the link token from the backend message nor the bearer token is logged + // 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!", "abc-link-token", "secret-token-xyz"} { + 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 for abc-link-token"), http.StatusInternalServerError, "error"), + errorcode.New(errorcode.GeneralException, "link manager unavailable"), http.StatusInternalServerError, "error"), Entry("SetLinkPassword: link not found", false, - errorcode.New(errorcode.ItemNotFound, "link abc-link-token not found"), http.StatusNotFound, "debug"), + errorcode.New(errorcode.ItemNotFound, "link not found"), http.StatusNotFound, "debug"), Entry("SetSpaceRootLinkPassword: internal error", true, - errorcode.New(errorcode.GeneralException, "link manager unavailable for abc-link-token"), http.StatusInternalServerError, "error"), + errorcode.New(errorcode.GeneralException, "link manager unavailable"), http.StatusInternalServerError, "error"), Entry("SetSpaceRootLinkPassword: link not found", true, - errorcode.New(errorcode.ItemNotFound, "link abc-link-token not found"), http.StatusNotFound, "debug"), + errorcode.New(errorcode.ItemNotFound, "link not found"), http.StatusNotFound, "debug"), ) checkDriveIDAndItemIDValidation := func(handler http.HandlerFunc) { diff --git a/services/graph/pkg/service/v0/base.go b/services/graph/pkg/service/v0/base.go index 397e6b8b6c..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.Debug().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.Debug().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.Debug().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/loglevel_test.go b/services/graph/pkg/service/v0/loglevel_test.go index 12ad140fcd..3fcdfd402f 100644 --- a/services/graph/pkg/service/v0/loglevel_test.go +++ b/services/graph/pkg/service/v0/loglevel_test.go @@ -1,18 +1,193 @@ 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 diff --git a/services/graph/pkg/service/v0/sharedbyme.go b/services/graph/pkg/service/v0/sharedbyme.go index 24e20f6458..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" ) @@ -17,11 +19,13 @@ type driveItemsByResourceID map[string]libregraph.DriveItem func (g Graph) GetSharedByMe(w http.ResponseWriter, r *http.Request) { ctx := r.Context() logger := g.logger.SubloggerWithRequestID(ctx) - logger.Debug().Msg("Calling GetRootDriveChildren") + 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 shares") + errorEvent(&logger, err).Msg("could not list user shares") errorcode.RenderError(w, r, err) return } @@ -29,7 +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 shares") + errorEvent(&logger, err).Msg("could not list ocm shares") errorcode.RenderError(w, r, err) return } @@ -37,7 +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 shares") + 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 809731b999..a33c116cd4 100644 --- a/services/graph/pkg/service/v0/sharedbyme_test.go +++ b/services/graph/pkg/service/v0/sharedbyme_test.go @@ -22,6 +22,7 @@ import ( . "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" @@ -312,7 +313,7 @@ var _ = Describe("sharedbyme", func() { return odataErr } - It("logs a gateway selection failure while listing shares once as error", func() { + 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) @@ -322,7 +323,15 @@ var _ = Describe("sharedbyme", func() { Expect(rr.Code).To(Equal(http.StatusInternalServerError)) Expect(odataError().Error.Code).To(Equal("generalException")) Expect(odataError().Error.Message).To(Equal("no gateway available")) - Expect(errorEntries()).To(HaveLen(1)) + // 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() { @@ -334,7 +343,9 @@ var _ = Describe("sharedbyme", func() { s := newLoggedService(gatewaySelector) r := httptest.NewRequest(http.MethodGet, "/graph/v1.0/me/drives/sharedByMe", nil) - s.GetSharedByMe(rr, r.WithContext(context.WithValue(r.Context(), middleware.RequestIDKey, "request-42"))) + 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")) @@ -342,13 +353,15 @@ var _ = Describe("sharedbyme", func() { entries := errorEntries() Expect(entries).To(HaveLen(1)) Expect(entries[0]).To(SatisfyAll( - Not(HaveKey("error")), + 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("does not log identity backend text when a share grantee lookup fails", + 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()) @@ -387,14 +400,11 @@ var _ = Describe("sharedbyme", func() { 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))) } - // neither the identity value nor the backend message reach the log - raw, err := json.Marshal(entries) - Expect(err).ToNot(HaveOccurred()) - Expect(string(raw)).ToNot(ContainSubstring("private-group-dn-42")) - Expect(string(raw)).ToNot(ContainSubstring("ldap search failed")) }, Entry("user share listing", func(identityClient *cs3mocks.GatewayAPIClient, resourceID *provider.ResourceId, groupGrantee *provider.Grantee) { @@ -447,10 +457,13 @@ var _ = Describe("sharedbyme", func() { gatewayClient.AssertNotCalled(GinkgoT(), "ListPublicShares", mock.Anything, mock.Anything) entries := errorEntries() Expect(entries).To(HaveLen(1)) - Expect(entries[0]).ToNot(HaveKey("error")) + 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 once as error", func() { + 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 @@ -466,7 +479,14 @@ var _ = Describe("sharedbyme", func() { 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) - Expect(errorEntries()).To(HaveLen(1)) + // 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() { @@ -481,21 +501,19 @@ var _ = Describe("sharedbyme", func() { Expect(rr.Code).To(Equal(http.StatusInternalServerError)) Expect(odataError().Error.Code).To(Equal("generalException")) - // the response is unchanged, only the log omits the backend message + // 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) - all := logEntries(logBuf) - entries := entriesAtLevel(all, "error") + entries := errorEntries() Expect(entries).To(HaveLen(1)) Expect(entries[0]).To(SatisfyAll( + HaveKeyWithValue("message", "could not list public shares"), HaveKeyWithValue("errorCode", "generalException"), - Not(HaveKey("error")), + HaveKeyWithValue("error", errorcode.New(errorcode.GeneralException, "listing failed for /Users/alice/Private/salary-2026.ods").Error()), )) - // the backend status message is not logged at any level - Expect(rawLog(all)).ToNot(ContainSubstring("salary-2026.ods")) }) - It("logs a gateway selection failure while listing public shares once as error", func() { + 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()) @@ -510,7 +528,14 @@ var _ = Describe("sharedbyme", func() { 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) - Expect(errorEntries()).To(HaveLen(1)) + // 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()), + ), + )) }) })