fix(userlog): harden the ocm share notifications

The provider of a federated sharer comes from the remote instance and
we put it into messageRich ourselves, which web renders as HTML. We
now only name it if it is a plain hostname. Otherwise the notification
says "Someone shared ... with you".

Looking up the federated sharer now has a timeout of 5 seconds, logs
why it failed and caches failed lookups as well, so a hanging invite
manager no longer blocks GET /notifications and a deleted federated
connection costs one lookup per request instead of one per
notification.

The acceptance scenario for the disabled "Share Removed" setting now
waits for the notification of a second share sent after the unshare
before it checks that the unshare notification did not show up.
Before, it checked once right after the 204 and passed even if the
setting was ignored.

Assisted-by: Claude Code:claude-opus-5-5
Signed-off-by: Jörn Friedrich Dreyer <jfd@butonic.de>
This commit is contained in:
Jörn Friedrich Dreyer committed 2026-12-04 16:48:17 +01:00
1 parent d7b309f9cf
commit f435d3b50d
6 files changed
+140 -20

No files matched your search

@@ -206,7 +206,7 @@ func (s *Service) sendSSE(ctx context.Context, userIDs []string, event events.Ev
continue
}
ev, err := service.NewConverter(ctx, loc, s.gatewaySelector, s.cfg.Service.Name, s.cfg.TranslationPath, s.cfg.DefaultLanguage).ConvertEvent(event.ID, event.Event)
ev, err := service.NewConverter(ctx, loc, s.gatewaySelector, s.cfg.Service.Name, s.cfg.TranslationPath, s.cfg.DefaultLanguage, s.log).ConvertEvent(event.ID, event.Event)
if err != nil {
if utils.IsErrNotFound(err) || utils.IsErrPermissionDenied(err) {
// the resource was not found, we assume it is deleted
+52 -14
View File
@@ -6,6 +6,7 @@ import (
"embed"
"encoding/json"
"fmt"
"regexp"
"strings"
"text/template"
"time"
@@ -25,6 +26,7 @@ import (
ocEvents "github.com/opencloud-eu/opencloud/pkg/events"
"github.com/opencloud-eu/opencloud/pkg/l10n"
"github.com/opencloud-eu/opencloud/pkg/log"
)
//go:embed l10n/locale
@@ -37,6 +39,12 @@ var (
_resourceTypeGlobal = "global"
_domain = "userlog"
// _ocmUserLookupTimeout limits how long converting a notification waits for the invite manager
_ocmUserLookupTimeout = 5 * time.Second
// _hostname matches a domain name or an IPv4 address, with an optional port
_hostname = regexp.MustCompile(`^[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*(:[0-9]{1,5})?$`)
)
// OC10Notification is the oc10 style representation of an event
@@ -63,6 +71,7 @@ type Converter struct {
translationPath string
defaultLanguage string
serviceAccountContext context.Context
logger log.Logger
// cached within one request not to query other service too much
spaces map[string]*storageprovider.StorageSpace
@@ -71,7 +80,7 @@ type Converter struct {
}
// NewConverter returns a new Converter
func NewConverter(ctx context.Context, loc string, gatewaySelector pool.Selectable[gateway.GatewayAPIClient], name, translationPath, defaultLanguage string) *Converter {
func NewConverter(ctx context.Context, loc string, gatewaySelector pool.Selectable[gateway.GatewayAPIClient], name, translationPath, defaultLanguage string, logger log.Logger) *Converter {
return &Converter{
locale: loc,
gatewaySelector: gatewaySelector,
@@ -79,6 +88,7 @@ func NewConverter(ctx context.Context, loc string, gatewaySelector pool.Selectab
translationPath: translationPath,
defaultLanguage: defaultLanguage,
serviceAccountContext: ctx,
logger: logger,
spaces: make(map[string]*storageprovider.StorageSpace),
users: make(map[string]*user.User),
resources: make(map[string]*storageprovider.ResourceInfo),
@@ -124,9 +134,9 @@ func (c *Converter) ConvertEvent(eventid string, event any) (OC10Notification, e
// ocm share related
case events.OCMCoreShareCreated:
return c.ocmShareMessage(eventid, ShareCreated, ShareCreatedByProvider, ev.Sharer, ev.GranteeUserID, ev.ShareID, ev.ResourceName, utils.TSToTime(ev.CTime))
return c.ocmShareMessage(eventid, ocmShareCreatedTemplates, ev.Sharer, ev.GranteeUserID, ev.ShareID, ev.ResourceName, utils.TSToTime(ev.CTime))
case events.OCMCoreShareDelete:
return c.ocmShareMessage(eventid, ShareRemoved, ShareRemovedByProvider, ev.Sharer, ev.Grantee, ev.ShareID, ev.ResourceName, utils.TSToTime(ev.CTime))
return c.ocmShareMessage(eventid, ocmShareRemovedTemplates, ev.Sharer, ev.Grantee, ev.ShareID, ev.ResourceName, utils.TSToTime(ev.CTime))
// misc
case ocEvents.ResourceMention:
@@ -322,13 +332,21 @@ func (c *Converter) shareMessage(eventid string, nt NotificationTemplate, execut
// resource lives on the remote instance, so we only know its name from the event. The resource
// details carry no id, clients would turn it into a link to a local resource.
//
// If the sharer cannot be resolved we use the providerNT template, which names the provider
// domain of the sharer instead of the user.
func (c *Converter) ocmShareMessage(eventid string, nt, providerNT NotificationTemplate, sharer *user.UserId, grantee *user.UserId, shareid string, resourcename string, ts time.Time) (OC10Notification, error) {
// If the sharer cannot be resolved we name the provider domain of the sharer instead of the
// user. The provider comes from the remote instance and clients render messageRich as HTML, so
// we only use it if it is a plain hostname.
func (c *Converter) ocmShareMessage(eventid string, nts ocmTemplates, sharer *user.UserId, grantee *user.UserId, shareid string, resourcename string, ts time.Time) (OC10Notification, error) {
usr := c.getOCMUser(sharer, grantee)
provider := sharer.GetIdp()
if usr == nil {
nt = providerNT
nt := nts.user
switch {
case usr != nil:
case _hostname.MatchString(provider):
nt = nts.provider
default:
c.logger.Warn().Str("provider", provider).Msg("the provider of the federated sharer is no hostname, not naming it in the notification")
nt = nts.unknown
provider = ""
}
subj, subjraw, msg, msgraw, err := composeMessage(nt, c.locale, c.defaultLanguage, c.translationPath, map[string]any{
@@ -339,7 +357,8 @@ func (c *Converter) ocmShareMessage(eventid string, nt, providerNT NotificationT
if err != nil {
return OC10Notification{}, err
}
// clients only know how to fill in the rich parameters, so we fill in the provider ourselves
// clients only know how to fill in the rich parameters, so we fill in the provider ourselves.
// It is a plain hostname, see above, so there is nothing to escape.
msgraw = strings.ReplaceAll(msgraw, "{provider}", provider)
details := generateDetails(usr, nil, nil, &collaboration.ShareId{OpaqueId: shareid})
@@ -363,15 +382,24 @@ func (c *Converter) ocmShareMessage(eventid string, nt, providerNT NotificationT
// getOCMUser looks up a federated user the grantee has accepted an invite from. It returns nil
// if the user cannot be resolved, e.g. because the federated connection was deleted. The
// federated id is no help then, it is the remote user id plus the issuer of the remote IdP,
// e.g. "<uuid>@https://cloud.example.org".
// e.g. "<uuid>@https://cloud.example.org". Failed lookups are cached as well, so we ask only
// once per sharer.
func (c *Converter) getOCMUser(sharer *user.UserId, grantee *user.UserId) *user.User {
key := ocmuser.FormatOCMUser(sharer)
if u, ok := c.users[key]; ok {
return u
}
u := c.lookupOCMUser(sharer, grantee)
c.users[key] = u
return u
}
func (c *Converter) lookupOCMUser(sharer *user.UserId, grantee *user.UserId) *user.User {
logger := c.logger.With().Str("sharer", ocmuser.FormatOCMUser(sharer)).Str("grantee", grantee.GetOpaqueId()).Logger()
gwc, err := c.gatewaySelector.Next()
if err != nil {
logger.Error().Err(err).Msg("cannot get gateway client to look up the federated sharer")
return nil
}
@@ -379,9 +407,12 @@ func (c *Converter) getOCMUser(sharer *user.UserId, grantee *user.UserId) *user.
// account would never match, so we call it without a token and pass the grantee as a filter.
filter, err := utils.MarshalProtoV1ToJSON(grantee)
if err != nil {
logger.Error().Err(err).Msg("cannot marshal the grantee to look up the federated sharer")
return nil
}
res, err := gwc.GetAcceptedUser(context.Background(), &invitepb.GetAcceptedUserRequest{
ctx, cancel := context.WithTimeout(context.Background(), _ocmUserLookupTimeout)
defer cancel()
res, err := gwc.GetAcceptedUser(ctx, &invitepb.GetAcceptedUserRequest{
RemoteUserId: sharer,
Opaque: &typespb.Opaque{
Map: map[string]*typespb.OpaqueEntry{
@@ -389,11 +420,18 @@ func (c *Converter) getOCMUser(sharer *user.UserId, grantee *user.UserId) *user.
},
},
})
if err != nil || res.GetStatus().GetCode() != rpc.Code_CODE_OK || res.GetRemoteUser() == nil {
switch {
case err != nil:
logger.Error().Err(err).Msg("cannot look up the federated sharer")
return nil
case res.GetStatus().GetCode() == rpc.Code_CODE_NOT_FOUND:
// e.g. the federated connection was deleted, nothing to worry about
logger.Debug().Msg("federated sharer not found")
return nil
case res.GetStatus().GetCode() != rpc.Code_CODE_OK:
logger.Error().Str("code", res.GetStatus().GetCode().String()).Str("message", res.GetStatus().GetMessage()).Msg("cannot look up the federated sharer")
return nil
}
c.users[key] = res.GetRemoteUser()
return res.GetRemoteUser()
}
@@ -17,6 +17,7 @@ import (
"github.com/stretchr/testify/mock"
"google.golang.org/grpc"
"github.com/opencloud-eu/opencloud/pkg/log"
"github.com/opencloud-eu/opencloud/services/userlog/pkg/service"
)
@@ -45,7 +46,7 @@ var _ = Describe("Converter", func() {
return gatewayClient
},
)
converter = service.NewConverter(context.Background(), "en", selector, "userlog", "", "en")
converter = service.NewConverter(context.Background(), "en", selector, "userlog", "", "en", log.NopLogger())
})
Describe("ocm shares", func() {
@@ -99,5 +100,43 @@ var _ = Describe("Converter", func() {
Expect(n.MessageDetails).ToNot(HaveKey("user"))
Expect(n.MessageDetails["resource"]).To(Equal(map[string]string{"name": "relativity"}))
})
It("does not name a provider that is no hostname", func() {
gatewayClient.On("GetAcceptedUser", mock.Anything, mock.Anything).Return(&invitepb.GetAcceptedUserResponse{
Status: &rpc.Status{Code: rpc.Code_CODE_NOT_FOUND},
}, nil)
n, err := converter.ConvertEvent("eventid", events.OCMCoreShareCreated{
ShareID: "shareid",
Sharer: &user.UserId{
Type: user.UserType_USER_TYPE_FEDERATED,
OpaqueId: "4c510ada-c86b-4815-8820-42cdf82c3d51@https://remote.example.org",
Idp: `<img src=x onerror="alert(1)">`,
},
GranteeUserID: grantee,
ResourceName: "relativity",
CTime: ctime,
})
Expect(err).ToNot(HaveOccurred())
Expect(n.Message).To(Equal("Someone shared relativity with you"))
Expect(n.MessageRaw).To(Equal("Someone shared {resource} with you"))
})
It("looks up a sharer that cannot be resolved only once", func() {
gatewayClient.On("GetAcceptedUser", mock.Anything, mock.Anything).Return(nil, context.DeadlineExceeded).Once()
for range 2 {
n, err := converter.ConvertEvent("eventid", events.OCMCoreShareDelete{
ShareID: "shareid",
Sharer: sharer,
Grantee: grantee,
ResourceName: "relativity",
CTime: ctime,
})
Expect(err).ToNot(HaveOccurred())
Expect(n.Message).To(Equal("Someone at remote.example.org unshared relativity with you"))
}
gatewayClient.AssertNumberOfCalls(GinkgoT(), "GetAcceptedUser", 1)
})
})
})
+1 -1
View File
@@ -74,7 +74,7 @@ func (s *Service) HandleGetEvents(w http.ResponseWriter, r *http.Request) {
return
}
conv := service.NewConverter(ctx, r.Header.Get(HeaderAcceptLanguage), s.gatewaySelector, s.cfg.Service.Name, s.cfg.TranslationPath, s.cfg.DefaultLanguage)
conv := service.NewConverter(ctx, r.Header.Get(HeaderAcceptLanguage), s.gatewaySelector, s.cfg.Service.Name, s.cfg.TranslationPath, s.cfg.DefaultLanguage, s.log)
var outdatedEvents []string
resp := GetEventResponseOC10{}
+28 -1
View File
@@ -49,17 +49,32 @@ var (
Message: l10n.Template("{user} unshared {resource} with you"),
}
// used for federated shares when the sharer cannot be resolved
// ShareCreatedByProvider is used for federated shares when the sharer cannot be resolved.
ShareCreatedByProvider = NotificationTemplate{
Subject: l10n.Template("Resource shared"),
Message: l10n.Template("Someone at {provider} shared {resource} with you"),
}
// ShareRemovedByProvider is used for federated unshares when the sharer cannot be resolved.
ShareRemovedByProvider = NotificationTemplate{
Subject: l10n.Template("Resource unshared"),
Message: l10n.Template("Someone at {provider} unshared {resource} with you"),
}
// ShareCreatedBySomeone is used for federated shares when neither the sharer nor its
// provider can be named.
ShareCreatedBySomeone = NotificationTemplate{
Subject: l10n.Template("Resource shared"),
Message: l10n.Template("Someone shared {resource} with you"),
}
// ShareRemovedBySomeone is used for federated unshares when neither the sharer nor its
// provider can be named.
ShareRemovedBySomeone = NotificationTemplate{
Subject: l10n.Template("Resource unshared"),
Message: l10n.Template("Someone unshared {resource} with you"),
}
Mention = NotificationTemplate{
Subject: l10n.Template("You have been mentioned"),
Message: l10n.Template("{user} mentioned you in {resource}"),
@@ -77,6 +92,18 @@ var (
)
// holds the information to turn the raw template into a parseable go template
// ocmTemplates are the templates for a federated share, depending on how much we know about the sharer
type ocmTemplates struct {
user NotificationTemplate
provider NotificationTemplate
unknown NotificationTemplate
}
var (
ocmShareCreatedTemplates = ocmTemplates{user: ShareCreated, provider: ShareCreatedByProvider, unknown: ShareCreatedBySomeone}
ocmShareRemovedTemplates = ocmTemplates{user: ShareRemoved, provider: ShareRemovedByProvider, unknown: ShareRemovedBySomeone}
)
var _placeholders = map[string]string{
"{user}": "{{ .username }}",
"{space}": "{{ .spacename }}",
@@ -49,16 +49,32 @@ Feature: federated users get in-app notifications about shares
| event | Share Removed |
| notificationTypes | in-app |
And using server "LOCAL"
And user "Alice" has created folder "anotherFolder"
And user "Alice" has sent the following resource share invitation to federated user:
| resource | folderToShare |
| space | Personal |
| sharee | Brian |
| shareType | user |
| permissionsRole | Viewer |
When user "Alice" removes the access of user "Brian" from resource "folderToShare" of space "Personal" using the Graph API
Then the HTTP status code should be "204"
And using server "REMOTE"
And user "Brian" should get a notification with subject "Resource shared" and message:
| message |
| Alice Hansen shared folderToShare with you |
And user "Brian" has deleted all notifications
And using server "LOCAL"
When user "Alice" removes the access of user "Brian" from resource "folderToShare" of space "Personal" using the Graph API
Then the HTTP status code should be "204"
# the share of anotherFolder reaches userlog after the unshare, so waiting for its notification
# gives the unshare the time to show up if the setting were ignored
When user "Alice" sends the following resource share invitation to federated user using the Graph API:
| resource | anotherFolder |
| space | Personal |
| sharee | Brian |
| shareType | user |
| permissionsRole | Viewer |
Then the HTTP status code should be "200"
And using server "REMOTE"
And user "Brian" should get a notification with subject "Resource shared" and message:
| message |
| Alice Hansen shared anotherFolder with you |
But user "Brian" should not have a notification related to resource "folderToShare" with subject "Resource unshared"