// Copyright 2018-2024 CERN // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // In applying this license, CERN does not waive the privileges and immunities // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. package ocmshareprovider // This package implements the OCM client API: it allows shares created on this Reva instance // to be sent to a remote EFSS system via OCM. import ( "context" "io" "net/url" "path/filepath" "slices" "time" userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1" ocm "github.com/cs3org/go-cs3apis/cs3/sharing/ocm/v1beta1" providerpb "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" typespb "github.com/cs3org/go-cs3apis/cs3/types/v1beta1" ocmim "github.com/cs3org/reva/v3/internal/grpc/services/ocminvitemanager" "github.com/cs3org/reva/v3/internal/http/services/opencloudmesh/ocmd" "github.com/cs3org/reva/v3/pkg/appctx" "github.com/cs3org/reva/v3/pkg/errtypes" ocmclient "github.com/cs3org/reva/v3/pkg/ocm/client" "github.com/cs3org/reva/v3/pkg/ocm/embedded" "github.com/cs3org/reva/v3/pkg/ocm/httpsig" "github.com/cs3org/reva/v3/pkg/ocm/providerdomain" "github.com/cs3org/reva/v3/pkg/ocm/share" "github.com/cs3org/reva/v3/pkg/ocm/share/repository/registry" "github.com/cs3org/reva/v3/pkg/plugin" "github.com/cs3org/reva/v3/pkg/rgrpc" "github.com/cs3org/reva/v3/pkg/rgrpc/status" revaservice "github.com/cs3org/reva/v3/pkg/service" "github.com/cs3org/reva/v3/pkg/sharedconf" "github.com/cs3org/reva/v3/pkg/storage/utils/walker" "github.com/cs3org/reva/v3/pkg/utils" "github.com/cs3org/reva/v3/pkg/utils/cfg" "github.com/pkg/errors" "google.golang.org/grpc" ) func init() { rgrpc.Register("ocmshareprovider", New) plugin.RegisterNamespace("grpc.services.ocmshareprovider.drivers", func(name string, newFunc any) { var f registry.NewFunc utils.Cast(newFunc, &f) registry.Register(name, f) }) plugin.RegisterNamespace("grpc.services.ocmshareprovider.embedded_drivers", func(name string, newFunc any) { var f embedded.NewFunc utils.Cast(newFunc, &f) embedded.Register(name, f) }) } type config struct { Driver string `mapstructure:"driver"` Drivers map[string]map[string]any `mapstructure:"drivers"` EmbeddedDriver string `mapstructure:"embedded_driver"` EmbeddedDrivers map[string]map[string]any `mapstructure:"embedded_drivers"` ClientTimeout int `mapstructure:"client_timeout"` ClientInsecure bool `mapstructure:"client_insecure"` GatewaySVC string `mapstructure:"gatewaysvc" validate:"required"` ProviderDomain string `docs:"The same domain registered in the provider authorizer" mapstructure:"provider_domain" validate:"required"` WebDAVEndpoint string `mapstructure:"webdav_endpoint" validate:"required"` Webapps []webapp `docs:";Web applications offered on outbound OCM shares, each with a name and the media types it opens. The webapp protocol is offered only if this list is not empty." mapstructure:"webapps"` WebAppEndpoint string `docs:";Absolute URL of the webapp opener. Required when webapps is not empty." mapstructure:"webapp_endpoint" validate:"required_with=Webapps"` SigningKey string `docs:";Path to the PEM file of the Ed25519 private key that signs the shares that this server sends. Use the key of the wellknown ocmprovider." mapstructure:"signing_key" validate:"required"` DisableDataTxAcceptance bool `docs:"false;Refuse acceptance of received shares that require a DATATX job." mapstructure:"disable_datatx_acceptance"` } type webapp struct { Name string `mapstructure:"name"` MediaTypes []string `mapstructure:"media_types"` } type service struct { conf *config repo share.Repository client *ocmd.OCMClient transferrer embedded.Transferrer signingKey *httpsig.Key notifier notifier } func (c *config) ApplyDefaults() { if c.Driver == "" { c.Driver = "json" } if c.EmbeddedDriver == "" { c.EmbeddedDriver = "webdav" } if c.ClientTimeout <= 0 { c.ClientTimeout = int(ocmclient.DefaultTransportConfig().Timeout / time.Second) } c.GatewaySVC = sharedconf.GetGatewaySVC(c.GatewaySVC) } func (s *service) Register(ss *grpc.Server) { ocm.RegisterOcmAPIServer(ss, s) } func getShareRepository(ctx context.Context, c *config) (share.Repository, error) { if f, ok := registry.NewFuncs[c.Driver]; ok { return f(ctx, c.Drivers[c.Driver]) } return nil, errtypes.NotFound("driver not found: " + c.Driver) } func getEmbeddedTransferrer(ctx context.Context, c *config) (embedded.Transferrer, error) { if f, ok := embedded.NewFuncs[c.EmbeddedDriver]; ok { return f(ctx, c.EmbeddedDrivers[c.EmbeddedDriver]) } return nil, errtypes.NotFound("embedded driver not found: " + c.EmbeddedDriver) } // New creates a new ocm share provider svc. func New(ctx context.Context, m map[string]any) (rgrpc.Service, error) { var c config decodeErr := cfg.Decode(m, &c) // Offer validation is ordered before the required_if decode error. if err := c.validateWebappOffer(); err != nil { return nil, err } if decodeErr != nil { return nil, decodeErr } // provider_domain is the identity of this server in every share and // notice, so it is checked before anything is allocated. providerDomain, err := providerdomain.CanonicalOCMHost(c.ProviderDomain) if err != nil { return nil, errors.New("ocmshareprovider: provider_domain is not an OCM host") } c.ProviderDomain = providerDomain repo, err := getShareRepository(ctx, &c) if err != nil { return nil, err } transferrer, err := getEmbeddedTransferrer(ctx, &c) if err != nil { return nil, err } key, err := httpsig.LoadKey(c.SigningKey) if err != nil { return nil, err } timeout := time.Duration(c.ClientTimeout) * time.Second ocmcl := ocmd.NewClient(timeout, c.ClientInsecure) notificationClient := ocmd.NewPublicOnlyClient(timeout, false) service := &service{ conf: &c, repo: repo, client: ocmcl, transferrer: transferrer, signingKey: key, notifier: &ocmd.AsyncNotifier{Client: notificationClient, Key: key}, } return service, nil } func (s *service) Close() error { if c, ok := s.notifier.(io.Closer); ok { return c.Close() } return nil } func (s *service) UnprotectedEndpoints() []string { return []string{"/cs3.sharing.ocm.v1beta1.OcmAPI/GetOCMShareByToken"} } func getResourceType(info *providerpb.ResourceInfo) string { switch info.Type { case providerpb.ResourceType_RESOURCE_TYPE_FILE: return "file" case providerpb.ResourceType_RESOURCE_TYPE_CONTAINER: return "folder" } return "unknown" } func sharedResourceType(info *providerpb.ResourceInfo) ocm.SharedResourceType { switch info.Type { case providerpb.ResourceType_RESOURCE_TYPE_FILE: return ocm.SharedResourceType_SHARE_RESOURCE_TYPE_FILE case providerpb.ResourceType_RESOURCE_TYPE_CONTAINER: return ocm.SharedResourceType_SHARE_RESOURCE_TYPE_CONTAINER } return ocm.SharedResourceType_SHARE_RESOURCE_TYPE_INVALID } func (s *service) webdavURL(share *ocm.Share) string { // the url is expected to be in the form https://ourserver/remote.php/dav/ocm/{ShareId}, see c.WebdavRoot in ocmprovider.go // TODO(lopresti) take the root from http.services.wellknown.ocmprovider's config p, _ := url.JoinPath(s.conf.WebDAVEndpoint, "/remote.php/dav/ocm", share.Id.OpaqueId) return p } func (s *service) getWebdavProtocol(share *ocm.Share, m *ocm.AccessMethod_WebdavOptions) *ocmd.WebDAV { var perms []string if m.WebdavOptions.Permissions.InitiateFileDownload { perms = append(perms, "read") } if m.WebdavOptions.Permissions.InitiateFileUpload { perms = append(perms, "write") } return &ocmd.WebDAV{ Permissions: perms, Requirements: m.WebdavOptions.Requirements, URI: s.webdavURL(share), SharedSecret: share.Token, } } // walk traverses the path recursively to discover all resources in the tree. func (s *service) walk(ctx context.Context, path string, fn walker.WalkFunc) error { gw, err := revaservice.Gateway(ctx) if err != nil { return err } return walker.NewWalker(gw).Walk(ctx, path, fn) } // return the protocols that can be used by remote users to access a local OCM share. // Access methods are already normalized. func (s *service) getProtocols(share *ocm.Share, apps []webapp) ocmd.Protocols { var p ocmd.Protocols for _, m := range share.AccessMethods { switch t := m.Term.(type) { case *ocm.AccessMethod_WebdavOptions: p = append(p, s.getWebdavProtocol(share, t)) case *ocm.AccessMethod_WebappOptions: p = append(p, s.getWebappProtocol(share, t, apps)) } } return p } func (s *service) CreateOCMShare(ctx context.Context, req *ocm.CreateOCMShareRequest) (*ocm.CreateOCMShareResponse, error) { log := appctx.GetLogger(ctx) gw, err := revaservice.Gateway(ctx) if err != nil { return &ocm.CreateOCMShareResponse{ Status: status.NewInternal(ctx, err, err.Error()), }, err } statRes, err := gw.Stat(ctx, &providerpb.StatRequest{ Ref: &providerpb.Reference{ ResourceId: req.ResourceId, }, }) if err != nil { return &ocm.CreateOCMShareResponse{ Status: status.NewInternal(ctx, err, err.Error()), }, err } if statRes.Status.Code != rpc.Code_CODE_OK { if statRes.Status.Code == rpc.Code_CODE_NOT_FOUND { return &ocm.CreateOCMShareResponse{ Status: status.NewNotFound(ctx, statRes.Status.Message), }, nil } return &ocm.CreateOCMShareResponse{ Status: statRes.Status, }, nil } info := statRes.Info // The type is stored with the share for its later notifications, so a // share without one is never created, remotely or locally. resourceType := sharedResourceType(info) if !share.SupportedResourceType(resourceType) { return &ocm.CreateOCMShareResponse{ Status: status.NewInvalidArg(ctx, "unsupported resource type"), }, nil } // The grantee host is validated as received, before any peer is contacted. grantee := req.GetGrantee().GetUserId() granteeHost, err := providerdomain.CanonicalOCMHost(grantee.GetIdp()) if err != nil || grantee.GetOpaqueId() == "" { return &ocm.CreateOCMShareResponse{ Status: status.NewInvalidArg(ctx, "invalid grantee"), }, nil } user := appctx.ContextMustGetUser(ctx) // lightweight homes are owned by service accounts that may not resolve to a user with the current user provider owner := info.Owner if owner.GetOpaqueId() == "" { owner = user.Id } tkn := utils.RandString(32) now := time.Now().UnixNano() ts := &typespb.Timestamp{ Seconds: uint64(now / 1000000000), Nanos: uint32(now % 1000000000), } ocmshare := &ocm.Share{ Token: tkn, Name: filepath.Base(info.Path), ResourceId: req.ResourceId, Grantee: req.Grantee, RecipientType: ocm.RecipientType_RECIPIENT_TYPE_USER, Owner: owner, Creator: user.Id, Ctime: ts, Mtime: ts, Expiration: req.Expiration, } // Since the share is persisted only after the remote server has accepted it, // check upfront whether it already exists: this avoids sending it to the // remote (and leaving a dangling share there) only to fail on the local // duplicate afterwards. switch _, err := s.repo.GetShare(ctx, user, &ocm.ShareReference{ Spec: &ocm.ShareReference_Key{ Key: &ocm.ShareKey{ Owner: owner, ResourceId: req.ResourceId, Grantee: req.Grantee, }, }, }); { case err == nil: return &ocm.CreateOCMShareResponse{ Status: status.NewAlreadyExists(ctx, share.ErrShareAlreadyExisting, "share already exists"), }, nil case !errors.Is(err, share.ErrShareNotFound): return &ocm.CreateOCMShareResponse{ Status: status.NewInternal(ctx, err, err.Error()), }, nil } // The share is persisted only once the remote server has accepted it, but // its ID is part of the payload sent there, so the ID is generated upfront. shareID, err := s.repo.GenerateID(ctx) if err != nil { return &ocm.CreateOCMShareResponse{ Status: status.NewInternal(ctx, err, err.Error()), }, nil } ocmshare.Id = shareID // look for the remote OCM endpoint ocmEndpoint, err := ocmim.GetOCMEndpoint(req.RecipientMeshProvider) if err != nil || ocmEndpoint == "" { return &ocm.CreateOCMShareResponse{ Status: status.NewInvalidArg(ctx, "the selected provider does not have an OCM endpoint"), }, nil } // and discover its resource types to understand how to send the share ocmUrl, _ := url.Parse(ocmEndpoint) ocmDisco, err := s.client.Discover(ctx, ocmUrl.Scheme+"://"+ocmUrl.Host) if err != nil { log.Error().Err(err).Msg("error discovering remote OCM provider capabilities") return &ocm.CreateOCMShareResponse{ Status: status.NewInternal(ctx, err, "error discovering remote OCM provider capabilities"), }, nil } // does the remote OCM server support the protocols and capabilities we're sending for this resource? // iterate over ocmDisco.ResourceTypes to look for protocol + '-receive' // and ocmDisco.Capabilities if we have requirements such as token exchange resType := getResourceType(info) webapp_supported := false for _, rt := range ocmDisco.ResourceTypes { if rt.Name != resType { continue } webappReceive, ok := rt.Protocols["webapp-receive"].(map[string]any) if !ok { continue } targets, ok := webappReceive["targets"].([]any) if !ok { continue } if slices.Contains(targets, "blank") { webapp_supported = true } // for webdav, we cannot assume this is present as until OCM 1.2 it was given for granted, // therefore we optimistically assume it's supported and move on // webdavReceive, ok := rt.Protocols["webdav-receive"].(map[string]any) } token_exchange_supported := false for _, caps := range ocmDisco.Capabilities { if caps == "exchange-token" { token_exchange_supported = true } } apps := s.webappsFor(info) methods, err := s.freshAccessMethods(ctx, req.AccessMethods, apps, webapp_supported, token_exchange_supported) if err != nil { return &ocm.CreateOCMShareResponse{ Status: status.NewInvalidArg(ctx, invalidShareAccessMethodsText), }, nil } ocmshare.AccessMethods = methods // An empty normalized protocol list fails before NewShare. protocols := s.getProtocols(ocmshare, apps) if len(protocols) == 0 { return &ocm.CreateOCMShareResponse{ Status: status.NewInvalidArg(ctx, webappOnlyNoProtocolText), }, nil } // prepare the request to be sent to the remote OCM server // Opaque IDs are sent as they are, even with an @ or a host suffix: // the receiver splits each address at its last @. newShareReq := &ocmd.NewShareRequest{ ShareWith: grantee.GetOpaqueId() + "@" + granteeHost, Name: ocmshare.Name, ProviderID: ocmshare.Id.OpaqueId, // FIXME: the owner host is not generally this server in case of resharing Owner: owner.OpaqueId + "@" + s.conf.ProviderDomain, Sender: user.Id.OpaqueId + "@" + s.conf.ProviderDomain, SenderDisplayName: user.DisplayName, ShareType: "user", ResourceType: resType, Protocols: protocols, } if req.Expiration != nil { newShareReq.Expiration = req.Expiration.Seconds } newShareRes, err := s.client.NewShare(ctx, ocmEndpoint, newShareReq, s.signingKey) if err != nil { switch { case errors.Is(err, ocmd.ErrInvalidParameters): return &ocm.CreateOCMShareResponse{ Status: status.NewInvalidArg(ctx, err.Error()), }, nil case errors.Is(err, ocmd.ErrServiceNotTrusted): return &ocm.CreateOCMShareResponse{ Status: status.NewInvalidArg(ctx, err.Error()), }, nil default: return &ocm.CreateOCMShareResponse{ Status: status.NewInternal(ctx, err, err.Error()), }, nil } } stored, err := s.repo.StoreShare(ctx, ocmshare, resourceType) if err != nil { // the remote server has already accepted the share, so a failure here // leaves a dangling share on the remote end log.Error().Err(err).Str("shareid", ocmshare.Id.OpaqueId).Msg("remote share created but persisting it locally failed") return &ocm.CreateOCMShareResponse{ Status: status.NewInternal(ctx, err, err.Error()), }, nil } res := &ocm.CreateOCMShareResponse{ Status: status.NewOK(ctx), Share: stored, RecipientDisplayName: newShareRes.RecipientDisplayName, } return res, nil } func (s *service) RemoveOCMShare(ctx context.Context, req *ocm.RemoveOCMShareRequest) (*ocm.RemoveOCMShareResponse, error) { user := appctx.ContextMustGetUser(ctx) removals, err := s.repo.DeleteShare(ctx, user, req.Ref) if err != nil { switch { case errors.Is(err, share.ErrShareNotFound): return &ocm.RemoveOCMShareResponse{ Status: status.NewNotFound(ctx, "share does not exist"), }, nil case errors.Is(err, share.ErrInvalidResourceType): return &ocm.RemoveOCMShareResponse{ Status: status.NewFailedPrecondition(ctx, err, "share has no supported resource type"), }, nil } return &ocm.RemoveOCMShareResponse{ Status: status.NewStatusFromErrType(ctx, "error removing share", err), }, nil } for i := range removals { s.notifyUnshared(ctx, &removals[i]) } return &ocm.RemoveOCMShareResponse{ Status: status.NewOK(ctx), }, nil } func (s *service) GetOCMShare(ctx context.Context, req *ocm.GetOCMShareRequest) (*ocm.GetOCMShareResponse, error) { // if the request is by token, the user does not need to be in the ctx var user *userpb.User if req.Ref.GetToken() == "" { user = appctx.ContextMustGetUser(ctx) } ocmshare, err := s.repo.GetShare(ctx, user, req.Ref) if err != nil { if errors.Is(err, share.ErrShareNotFound) { return &ocm.GetOCMShareResponse{ Status: status.NewNotFound(ctx, "share does not exist"), }, nil } return &ocm.GetOCMShareResponse{ Status: status.NewStatusFromErrType(ctx, "error getting share", err), }, nil } return &ocm.GetOCMShareResponse{ Status: status.NewOK(ctx), Share: ocmshare, }, nil } func (s *service) GetOCMShareByToken(ctx context.Context, req *ocm.GetOCMShareByTokenRequest) (*ocm.GetOCMShareByTokenResponse, error) { ocmshare, err := s.repo.GetShare(ctx, nil, &ocm.ShareReference{ Spec: &ocm.ShareReference_Token{ Token: req.Token, }, }) if err != nil { if errors.Is(err, share.ErrShareNotFound) { return &ocm.GetOCMShareByTokenResponse{ Status: status.NewNotFound(ctx, "share does not exist"), }, nil } return &ocm.GetOCMShareByTokenResponse{ Status: status.NewStatusFromErrType(ctx, "error getting share", err), }, nil } return &ocm.GetOCMShareByTokenResponse{ Status: status.NewOK(ctx), Share: ocmshare, }, nil } func (s *service) ListOCMShares(ctx context.Context, req *ocm.ListOCMSharesRequest) (*ocm.ListOCMSharesResponse, error) { user := appctx.ContextMustGetUser(ctx) shares, err := s.repo.ListShares(ctx, user, req.Filters) if err != nil { return &ocm.ListOCMSharesResponse{ Status: status.NewStatusFromErrType(ctx, "error listing shares", err), }, nil } res := &ocm.ListOCMSharesResponse{ Status: status.NewOK(ctx), Shares: shares, } return res, nil } func (s *service) UpdateOCMShare(ctx context.Context, req *ocm.UpdateOCMShareRequest) (*ocm.UpdateOCMShareResponse, error) { user := appctx.ContextMustGetUser(ctx) if len(req.Field) == 0 { return &ocm.UpdateOCMShareResponse{ Status: status.NewOK(ctx), }, nil } update, err := s.repo.UpdateShare(ctx, user, req.Ref, req.Field...) if err != nil { switch { case errors.Is(err, share.ErrShareNotFound): return &ocm.UpdateOCMShareResponse{ Status: status.NewNotFound(ctx, "share does not exist"), }, nil case errors.Is(err, share.ErrInvalidResourceType): return &ocm.UpdateOCMShareResponse{ Status: status.NewFailedPrecondition(ctx, err, "share has no supported resource type"), }, nil } return &ocm.UpdateOCMShareResponse{ Status: status.NewStatusFromErrType(ctx, "error updating share", err), }, nil } s.notifyPermissionChange(ctx, update, req.GetField()) res := &ocm.UpdateOCMShareResponse{ Status: status.NewOK(ctx), } return res, nil } func (s *service) ListReceivedOCMShares(ctx context.Context, req *ocm.ListReceivedOCMSharesRequest) (*ocm.ListReceivedOCMSharesResponse, error) { user := appctx.ContextMustGetUser(ctx) shares, err := s.repo.ListReceivedShares(ctx, user, req.Filters) if err != nil { return &ocm.ListReceivedOCMSharesResponse{ Status: status.NewStatusFromErrType(ctx, "error listing received shares", err), }, nil } res := &ocm.ListReceivedOCMSharesResponse{ Status: status.NewOK(ctx), Shares: shares, } return res, nil } func (s *service) UpdateReceivedOCMShare(ctx context.Context, req *ocm.UpdateReceivedOCMShareRequest) (*ocm.UpdateReceivedOCMShareResponse, error) { user := appctx.ContextMustGetUser(ctx) transferAcceptance := false // Accepting a share with embedded content holds it in TRANSFERRING until // the copy completes. Only a state the mask asks to change can start it. // The stored grant, not the request, tells if the share is embedded, so // an embedded share never becomes ACCEPTED without a completed copy. if slices.Contains(req.GetUpdateMask().GetPaths(), "state") && req.Share.State == ocm.ShareState_SHARE_STATE_ACCEPTED { current, err := s.repo.GetReceivedShare(ctx, user, &ocm.ShareReference{ Spec: &ocm.ShareReference_Id{Id: req.Share.GetId()}, }) if err != nil { if errors.Is(err, share.ErrShareNotFound) { return &ocm.UpdateReceivedOCMShareResponse{ Status: status.NewNotFound(ctx, "share does not exist"), }, nil } return &ocm.UpdateReceivedOCMShareResponse{ Status: status.NewStatusFromErrType(ctx, "error getting received share", err), }, nil } if slices.ContainsFunc(current.GetProtocols(), func(p *ocm.Protocol) bool { return p.GetEmbeddedOptions() != nil }) { return s.processEmbeddedShare(ctx, user, req) } transferAcceptance = share.DataTransferProtocol(current) != nil if s.conf.DisableDataTxAcceptance && transferAcceptance { return &ocm.UpdateReceivedOCMShareResponse{ Status: status.NewUnimplemented(ctx, nil, "DATATX share acceptance is disabled"), }, nil } } update, err := s.repo.UpdateReceivedShare(ctx, user, req.Share, req.UpdateMask) if err != nil { if errors.Is(err, share.ErrShareNotFound) { return &ocm.UpdateReceivedOCMShareResponse{ Status: status.NewNotFound(ctx, "share does not exist"), }, nil } return &ocm.UpdateReceivedOCMShareResponse{ Status: status.NewStatusFromErrType(ctx, "error updating received share", err), }, nil } // Legacy DATATX updates the grant before the scheduler acknowledges a job. if !transferAcceptance { s.notifyReceivedState(ctx, update, true) } res := &ocm.UpdateReceivedOCMShareResponse{ Status: status.NewOK(ctx), } return res, nil } // processEmbeddedShare starts a transfer attempt. The share becomes ACCEPTED // once every file arrived, or REJECTED if the transfer failed. Without a // destination, a payload or a transferrer, the share stays unchanged. func (s *service) processEmbeddedShare(ctx context.Context, user *userpb.User, req *ocm.UpdateReceivedOCMShareRequest) (*ocm.UpdateReceivedOCMShareResponse, error) { recvShare := req.Share if recvShare.Destination == "" { return &ocm.UpdateReceivedOCMShareResponse{ Status: status.NewFailedPrecondition(ctx, nil, "embedded share needs a destination"), }, nil } if s.transferrer == nil { return &ocm.UpdateReceivedOCMShareResponse{ Status: status.NewFailedPrecondition(ctx, nil, "embedded transfers are not configured"), }, nil } payload, err := s.repo.GetEmbeddedPayload(ctx, user, recvShare) if err != nil { if errors.Is(err, share.ErrShareNotFound) { return &ocm.UpdateReceivedOCMShareResponse{ Status: status.NewNotFound(ctx, "share does not exist"), }, nil } return &ocm.UpdateReceivedOCMShareResponse{ Status: status.NewStatusFromErrType(ctx, "error retrieving embedded share payload", err), }, nil } if payload == "" { return &ocm.UpdateReceivedOCMShareResponse{ Status: status.NewFailedPrecondition(ctx, nil, "embedded share has no payload"), }, nil } // The start is atomic, so a second start fails instead of racing on the // same destination. start, err := s.repo.StartReceivedShareTransfer(ctx, user, recvShare, req.UpdateMask) if err != nil { switch { case errors.Is(err, share.ErrShareNotFound): return &ocm.UpdateReceivedOCMShareResponse{ Status: status.NewNotFound(ctx, "share does not exist"), }, nil case errors.Is(err, share.ErrTransferInProgress): return &ocm.UpdateReceivedOCMShareResponse{ Status: status.NewFailedPrecondition(ctx, err, "transfer already in progress"), }, nil case errors.Is(err, share.ErrShareAlreadyAccepted): return &ocm.UpdateReceivedOCMShareResponse{ Status: status.NewFailedPrecondition(ctx, err, "share already accepted"), }, nil } return &ocm.UpdateReceivedOCMShareResponse{ Status: status.NewStatusFromErrType(ctx, "error updating received share", err), }, nil } id := start.Share.GetId() generation := start.Generation // The transfer outlives this request, so detach the context from its // cancellation while keeping its values (user, auth token, logger). detached := context.WithoutCancel(ctx) onComplete := func(transferErr error) { log := appctx.GetLogger(detached) defer func() { if r := recover(); r != nil { log.Error().Interface("error", r).Msg("failure while ending an embedded transfer") } }() state := ocm.ShareState_SHARE_STATE_ACCEPTED if transferErr != nil { log.Error().Err(transferErr).Msg("embedded transfer failed, rejecting share") state = ocm.ShareState_SHARE_STATE_REJECTED } if err := s.endTransfer(detached, user, id, generation, state); err != nil { log.Error().Err(err).Msg("error updating received share after embedded transfer") } } if err := s.transferrer.Process(ctx, payload, recvShare.Destination, onComplete); err != nil { // The transfer never started, so don't leave the share behind as transferring. if err := s.endTransfer(ctx, user, id, generation, ocm.ShareState_SHARE_STATE_REJECTED); err != nil { appctx.GetLogger(ctx).Error().Err(err).Msg("error rejecting received share") } return &ocm.UpdateReceivedOCMShareResponse{ Status: status.NewStatusFromErrType(ctx, "error processing embedded share", err), }, nil } return &ocm.UpdateReceivedOCMShareResponse{ Status: status.NewOK(ctx), }, nil } // endTransfer completes one transfer attempt, unless a reset or a newer // attempt replaced it. A failed transfer is not the recipient declining. func (s *service) endTransfer(ctx context.Context, user *userpb.User, id *ocm.ShareId, generation uint64, state ocm.ShareState) error { update, err := s.repo.CompleteReceivedShareTransfer(ctx, user, id, generation, state) if err != nil { return err } if !update.StateChanged() { appctx.GetLogger(ctx).Info(). Str("state", update.After.GetState().String()). Msg("transfer attempt is no longer current, leaving the share untouched") return nil } s.notifyReceivedState(ctx, update, false) return nil } func (s *service) GetReceivedOCMShare(ctx context.Context, req *ocm.GetReceivedOCMShareRequest) (*ocm.GetReceivedOCMShareResponse, error) { user := appctx.ContextMustGetUser(ctx) ocmshare, err := s.repo.GetReceivedShare(ctx, user, req.Ref) if err != nil { if errors.Is(err, share.ErrShareNotFound) { return &ocm.GetReceivedOCMShareResponse{ Status: status.NewNotFound(ctx, "share does not exist"), }, nil } return &ocm.GetReceivedOCMShareResponse{ Status: status.NewStatusFromErrType(ctx, "error getting received share", err), }, nil } res := &ocm.GetReceivedOCMShareResponse{ Status: status.NewOK(ctx), Share: ocmshare, } return res, nil }