From 1373c6711ef08261ed8f3445025d347269407ae9 Mon Sep 17 00:00:00 2001 From: Mahdi Baghbani Date: Wed, 25 Nov 2026 07:59:44 +0000 Subject: [PATCH 1/8] feat(ocm): add directed SQL share actions Signed-off-by: Mahdi Baghbani --- pkg/ocm/share/contact.go | 34 ++ pkg/share/manager/sql/model/model.go | 4 + pkg/share/manager/sql/ocm_contact.go | 207 +++++++ .../manager/sql/ocm_directed_actions_test.go | 531 ++++++++++++++++++ .../sql/ocm_directed_concurrency_test.go | 229 ++++++++ pkg/share/manager/sql/ocm_shares.go | 101 +++- pkg/share/manager/sql/ocm_withdrawal_test.go | 2 +- 7 files changed, 1076 insertions(+), 32 deletions(-) create mode 100644 pkg/ocm/share/contact.go create mode 100644 pkg/share/manager/sql/ocm_contact.go create mode 100644 pkg/share/manager/sql/ocm_directed_actions_test.go create mode 100644 pkg/share/manager/sql/ocm_directed_concurrency_test.go diff --git a/pkg/ocm/share/contact.go b/pkg/ocm/share/contact.go new file mode 100644 index 00000000000..db971a43c57 --- /dev/null +++ b/pkg/ocm/share/contact.go @@ -0,0 +1,34 @@ +// Copyright 2018-2026 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 share + +import ( + "context" + + userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" +) + +// DirectedShareActions is the transactional bulk surface of a repository: +// withdraw exact bound outgoing grants and reject exact bound received grants. +// Each direction either commits its whole captured selection or reports an +// error without an acknowledged receipt. +type DirectedShareActions interface { + RemoveOCMSharesForRecipient(ctx context.Context, creator, recipient *userpb.UserId) ([]*ShareRemoval, error) + RejectReceivedOCMSharesFromSender(ctx context.Context, recipient, sender *userpb.UserId) ([]*ReceivedShareUpdate, error) +} diff --git a/pkg/share/manager/sql/model/model.go b/pkg/share/manager/sql/model/model.go index 6a627bb4d74..d85fd11e786 100644 --- a/pkg/share/manager/sql/model/model.go +++ b/pkg/share/manager/sql/model/model.go @@ -212,6 +212,10 @@ type ShareState struct { // In addition, tokens must be unique. // TODO(lopresti) see if we can consolidate Owner and Initiator with UIDOwner and UIDInitiator in ProtoShare type OcmShare struct { + CreatorIdp []byte `gorm:"type:varbinary(1020);index:i_ocmshare_directed,priority:1"` + CreatorUserType int32 `gorm:"not null;default:0"` + CreatorTenant []byte `gorm:"type:varbinary(1020)"` + RemoteRecipient []byte `gorm:"type:varbinary(1025);index:i_ocmshare_directed,priority:2"` ProtoShare DeletedAt gorm.DeletedAt `gorm:"uniqueIndex:u_ocmshare"` // the composite index also works as regular index here, similarly as in the `Share` struct Inode string `gorm:"size:64;not null;uniqueIndex:u_ocmshare;index"` diff --git a/pkg/share/manager/sql/ocm_contact.go b/pkg/share/manager/sql/ocm_contact.go new file mode 100644 index 00000000000..d9a8dc5cfb9 --- /dev/null +++ b/pkg/share/manager/sql/ocm_contact.go @@ -0,0 +1,207 @@ +// Copyright 2018-2026 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 sql + +// Directed bulk share actions. Each direction captures its exact selection +// inside one transaction and either commits all of it or returns without an +// acknowledged receipt. Grants created outside the captured set are later +// separate shares; no pair-wide authority is recorded here. + +import ( + "context" + "slices" + "time" + + userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" + ocm "github.com/cs3org/go-cs3apis/cs3/sharing/ocm/v1beta1" + "github.com/cs3org/reva/v3/pkg/errtypes" + "github.com/cs3org/reva/v3/pkg/ocm/providerdomain" + "github.com/cs3org/reva/v3/pkg/ocm/share" + model "github.com/cs3org/reva/v3/pkg/share/manager/sql/model" + "gorm.io/gorm" +) + +// RemoveOCMSharesForRecipient uses the bound creator identity, including tenant, +// because a resource owner or a same-opaque principal may be a different user. +func (m *mgr) RemoveOCMSharesForRecipient(ctx context.Context, creator, recipient *userpb.UserId) ([]*share.ShareRemoval, error) { + if creator.GetOpaqueId() == "" || creator.GetIdp() == "" || creator.GetType() == userpb.UserType_USER_TYPE_INVALID || recipient.GetOpaqueId() == "" { + return nil, errtypes.BadRequest("invalid directed share action identity") + } + remoteHost, err := providerdomain.CanonicalOCMHost(recipient.GetIdp()) + if err != nil { + return nil, errtypes.BadRequest("invalid recipient provider host") + } + var receipts []*share.ShareRemoval + var check commitCheck + err = m.transact(ctx, "remove_shares_for_recipient", func(tx *gorm.DB) error { + receipts = nil + check = commitCheck{} + q := forUpdate(tx). + Where("creator_idp = ? AND remote_recipient = ? AND initiator = ? AND creator_user_type = ? AND creator_tenant = ? AND recipient_type = ?", + []byte(creator.GetIdp()), []byte(recipient.GetOpaqueId()+"@"+remoteHost), creator.GetOpaqueId(), int32(creator.GetType()), []byte(creator.GetTenantId()), model.OcmShareTypeUser). + Order("id") + var selected []model.OcmShare + if err := q.Find(&selected).Error; err != nil { + return err + } + if len(selected) == 0 { + return nil + } + ids := make([]uint, 0, len(selected)) + authorized := make([]model.OcmShare, 0, len(selected)) + for _, sm := range selected { + // MySQL may collate the ordinary initiator column non-binarily. + if sm.Initiator != creator.GetOpaqueId() { + continue + } + if !share.SupportedResourceType(convertToCS3SharedResourceType(sm.ItemType)) { + return share.ErrInvalidResourceType + } + ids = append(ids, sm.Id) + authorized = append(authorized, sm) + methods, err := accessMethodsTx(tx, sm.Id) + if err != nil { + return err + } + receipts = append(receipts, &share.ShareRemoval{Share: convertToCS3OCMShare(&sm, methods), ResourceType: convertToCS3SharedResourceType(sm.ItemType)}) + } + if len(ids) == 0 { + return nil + } + if err := deleteLockedOCMShares(tx, authorized, errtypes.Conflict("selected share changed")); err != nil { + return err + } + check.observe = func(db *gorm.DB) (share.CommitObservation, error) { + var active int64 + if err := db.Model(&model.OcmShare{}).Where("id IN ?", ids).Count(&active).Error; err != nil { + return share.CommitObservedUnread, err + } + if active == 0 { + return share.CommitObservedRequested, nil + } + return share.CommitObservedOther, nil + } + return nil + }, &check) + if err != nil { + return nil, err + } + return receipts, nil +} + +// RejectReceivedOCMSharesFromSender applies local recipient intent to active projections. +func (m *mgr) RejectReceivedOCMSharesFromSender(ctx context.Context, recipient, sender *userpb.UserId) ([]*share.ReceivedShareUpdate, error) { + if recipient.GetOpaqueId() == "" || recipient.GetIdp() == "" || recipient.GetType() == userpb.UserType_USER_TYPE_INVALID || sender.GetOpaqueId() == "" { + return nil, errtypes.BadRequest("invalid directed share action identity") + } + senderHost, err := share.CanonicalGrantOrigin(sender.GetIdp()) + if err != nil { + return nil, errtypes.BadRequest("invalid sender provider host") + } + var receipts []*share.ReceivedShareUpdate + var check commitCheck + err = m.transact(ctx, "reject_received_from_sender", func(tx *gorm.DB) error { + receipts = nil + check = commitCheck{} + var selected []model.OcmReceivedShare + senderAddress := sender.GetOpaqueId() + "@" + senderHost + if err := forUpdate(tx). + Where("initiator = ? AND share_with = ? AND share_with_idp = ? AND share_with_tenant = ? AND recipient_user_type = ? AND recipient_type = ?", + senderAddress, recipient.GetOpaqueId(), recipient.GetIdp(), recipient.GetTenantId(), int32(recipient.GetType()), model.OcmShareTypeUser). + Where("state IN ?", []model.OcmShareState{model.OcmShareStatePending, model.OcmShareStateAccepted, model.OcmShareStateTransferring}). + Order("id").Find(&selected).Error; err != nil { + return err + } + if len(selected) == 0 { + return nil + } + type stateSnapshot struct { + State model.OcmShareState + Hidden bool + TransferGeneration uint64 + } + ids := make([]uint, 0, len(selected)) + previous := make([]stateSnapshot, 0, len(selected)) + expected := make([]stateSnapshot, 0, len(selected)) + for _, row := range selected { + if row.Initiator != senderAddress || row.ShareWith != recipient.GetOpaqueId() || + row.ShareWithIdp != recipient.GetIdp() || row.ShareWithTenant != recipient.GetTenantId() { + // The inherited text columns may match under a looser collation. + continue + } + key, err := share.GrantKey(senderHost, row.RemoteShareID) + if err != nil || row.GrantKey == nil || *row.GrantKey != key { + return share.ErrGrantIdentityMismatch + } + if !share.SupportedResourceType(convertToCS3SharedResourceType(row.ItemType)) { + return share.ErrInvalidResourceType + } + protocols, err := protocolsTx(tx, row.ID) + if err != nil { + return err + } + before := convertToCS3OCMReceivedShare(&row, protocols) + previous = append(previous, stateSnapshot{row.State, row.Hidden, row.TransferGeneration}) + if err := updateReceivedFields(tx, &row, map[string]any{ + "state": model.OcmShareStateRejected, "hidden": true, "mtime": time.Now().Unix(), + }); err != nil { + return err + } + applied, err := readReceivedProjection(tx, row.ID) + if err != nil { + return err + } + if applied == nil { + return share.ErrShareNotFound + } + var appliedProtocols []*ocm.Protocol + for i := range applied.protocols { + appliedProtocols = append(appliedProtocols, convertToCS3Protocol(&applied.protocols[i])) + } + after := convertToCS3OCMReceivedShare(&applied.row, appliedProtocols) + ids = append(ids, row.ID) + expected = append(expected, stateSnapshot{applied.row.State, applied.row.Hidden, applied.row.TransferGeneration}) + receipts = append(receipts, &share.ReceivedShareUpdate{Before: before, After: after}) + } + if len(ids) == 0 { + return nil + } + check.observe = func(db *gorm.DB) (share.CommitObservation, error) { + var observed []stateSnapshot + err := db.Model(&model.OcmReceivedShare{}).Select("state", "hidden", "transfer_generation"). + Where("id IN ?", ids).Order("id").Find(&observed).Error + if err != nil { + return share.CommitObservedUnread, err + } + switch { + case slices.Equal(observed, expected): + return share.CommitObservedRequested, nil + case slices.Equal(observed, previous): + return share.CommitObservedPrevious, nil + default: + return share.CommitObservedOther, nil + } + } + return nil + }, &check) + if err != nil { + return nil, err + } + return receipts, nil +} diff --git a/pkg/share/manager/sql/ocm_directed_actions_test.go b/pkg/share/manager/sql/ocm_directed_actions_test.go new file mode 100644 index 00000000000..5d8e630635c --- /dev/null +++ b/pkg/share/manager/sql/ocm_directed_actions_test.go @@ -0,0 +1,531 @@ +// Copyright 2018-2026 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. + +package sql + +import ( + "context" + "encoding/json" + "errors" + "strings" + "testing" + "time" + + userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" + ocm "github.com/cs3org/go-cs3apis/cs3/sharing/ocm/v1beta1" + provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" + "github.com/cs3org/reva/v3/pkg/ocm/share" + "github.com/cs3org/reva/v3/pkg/share/manager/sql/model" + "google.golang.org/genproto/protobuf/field_mask" + "gorm.io/gorm" +) + +func TestDirectedActionsRespectExactIdentities(t *testing.T) { + forEachDialectConfig(t, func(t *testing.T, cfg map[string]any) { + ctx := context.Background() + m := openOCMManager(t, cfg) + alice := &userpb.UserId{OpaqueId: "00012", Idp: "Directory", TenantId: "Tenant", Type: userpb.UserType_USER_TYPE_PRIMARY} + otherDirectory := &userpb.UserId{OpaqueId: "00012", Idp: "directory", TenantId: "Tenant", Type: userpb.UserType_USER_TYPE_PRIMARY} + otherSpace := &userpb.UserId{OpaqueId: "00012", Idp: "Directory ", TenantId: "Tenant", Type: userpb.UserType_USER_TYPE_PRIMARY} + otherOpaqueSpace := &userpb.UserId{OpaqueId: "00012 ", Idp: "Directory", TenantId: "Tenant", Type: userpb.UserType_USER_TYPE_PRIMARY} + otherType := &userpb.UserId{OpaqueId: "00012", Idp: "Directory", TenantId: "Tenant", Type: userpb.UserType_USER_TYPE_FEDERATED} + otherTenant := &userpb.UserId{OpaqueId: "00012", Idp: "Directory", TenantId: "tenant", Type: userpb.UserType_USER_TYPE_PRIMARY} + bob := &userpb.UserId{OpaqueId: "bob", Idp: "remote.example.org:8443", Type: userpb.UserType_USER_TYPE_FEDERATED} + otherHost := &userpb.UserId{OpaqueId: "bob", Idp: "remote.example.org", Type: userpb.UserType_USER_TYPE_FEDERATED} + store := func(creator, remote *userpb.UserId, token, resource string) *ocm.Share { + t.Helper() + grantee := &provider.Grantee{Type: provider.GranteeType_GRANTEE_TYPE_USER, Id: &provider.Grantee_UserId{UserId: remote}} + s := getOcmShare(getOcmAccessMethods("viewer"), grantee, creator, &provider.ResourceId{StorageId: "storage", OpaqueId: resource}, token) + s.RecipientType = ocm.RecipientType_RECIPIENT_TYPE_USER + id, err := m.GenerateID(ctx) + if err != nil { + t.Fatal(err) + } + s.Id = id + if _, err := m.StoreShare(ctx, s, file); err != nil { + t.Fatal(err) + } + return s + } + aliceUser := &userpb.User{Id: alice} + upperHostBob := &userpb.UserId{OpaqueId: "bob", Idp: "REMOTE.example.org:8443", Type: bob.Type} + cutoff := time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC) + clock := cutoff + m.db = m.db.Session(&gorm.Session{NowFunc: func() time.Time { return clock }}) + prior := store(alice, upperHostBob, "prior", "z-shared") + if _, err := m.DeleteShare(ctx, aliceUser, idRef(prior.Id)); err != nil { + t.Fatal(err) + } + clock = cutoff.Add(time.Second) + otherPrior := store(alice, bob, "other-prior", "a-other") + if _, err := m.DeleteShare(ctx, aliceUser, idRef(otherPrior.Id)); err != nil { + t.Fatal(err) + } + clock = cutoff + selected := store(alice, upperHostBob, "selected", "z-shared") + secondKey := store(alice, bob, "second-key", "a-other") + duplicate := store(alice, upperHostBob, "duplicate", "z-shared") + wrongDirectory := store(otherDirectory, upperHostBob, "other-directory", "z-shared") + wrongSpace := store(otherSpace, bob, "other-space", "other-space") + wrongOpaqueSpace := store(otherOpaqueSpace, bob, "other-opaque-space", "other-opaque-space") + wrongType := store(otherType, bob, "other-type", "other-type") + wrongHost := store(alice, otherHost, "other-host", "other-host") + wrongTenant := store(otherTenant, bob, "other-tenant", "other-tenant") + unboundOutgoing := store(alice, bob, "unbound", "unbound") + if err := m.db.Model(&model.OcmShare{}).Where("id = ?", unboundOutgoing.Id.OpaqueId). + Update("creator_user_type", userpb.UserType_USER_TYPE_INVALID).Error; err != nil { + t.Fatal(err) + } + group := store(alice, bob, "group", "group") + if err := m.db.Model(&model.OcmShare{}).Where("id = ?", group.Id.OpaqueId).Update("recipient_type", model.OcmShareTypeGroup).Error; err != nil { + t.Fatal(err) + } + const callback = "test:abort-second-directed-delete" + abort := errors.New("abort after second directed delete") + deletes := 0 + if err := m.db.Callback().Delete().After("gorm:delete").Register(callback, func(tx *gorm.DB) { + if tx.Error == nil && tx.RowsAffected == 1 { + deletes++ + if deletes == 2 { + _ = tx.AddError(abort) + } + } + }); err != nil { + t.Fatal(err) + } + rolledBack, err := m.RemoveOCMSharesForRecipient(ctx, alice, bob) + if removeErr := m.db.Callback().Delete().Remove(callback); removeErr != nil { + t.Fatal(removeErr) + } + if !errors.Is(err, abort) || rolledBack != nil || deletes != 2 { + t.Fatalf("rollback returned %d receipts after %d writes: %v", len(rolledBack), deletes, err) + } + for _, grant := range []*ocm.Share{selected, secondKey, duplicate} { + if _, err := m.GetShare(ctx, aliceUser, idRef(grant.Id)); err != nil { + t.Fatalf("grant %s unavailable after rollback: %v", grant.Id.OpaqueId, err) + } + } + removed, err := m.RemoveOCMSharesForRecipient(ctx, alice, bob) + want := []struct { + grant *ocm.Share + deletedAt time.Time + }{ + {selected, cutoff.Add(time.Millisecond)}, + {secondKey, cutoff.Add(time.Second + time.Millisecond)}, + {duplicate, cutoff.Add(2 * time.Millisecond)}, + } + if err != nil || len(removed) != len(want) { + t.Fatalf("withdraw receipts %v: %v", removed, err) + } + for i, entry := range want { + id := entry.grant.Id + if receipt := removed[i]; receipt.ResourceType != file || receipt.Share.Id.OpaqueId != id.OpaqueId || receipt.Share.Token != entry.grant.Token { + t.Errorf("receipt %d does not describe grant %s", i, id.OpaqueId) + } + var row model.OcmShare + if err := m.db.Unscoped().Where("id = ?", id.OpaqueId).Take(&row).Error; err != nil || + !row.DeletedAt.Valid || !row.DeletedAt.Time.Equal(entry.deletedAt) { + t.Errorf("grant %s deletion timestamp %v, want %v: %v", id.OpaqueId, row.DeletedAt, entry.deletedAt, err) + } + if _, err := m.GetShare(ctx, aliceUser, idRef(id)); !errors.Is(err, share.ErrShareNotFound) { + t.Errorf("withdrawn grant %s lookup = %v", id.OpaqueId, err) + } + } + if repeated, err := m.RemoveOCMSharesForRecipient(ctx, alice, bob); err != nil || len(repeated) != 0 { + t.Fatalf("repeat withdrawal receipts %v: %v", repeated, err) + } + for _, survivor := range []*ocm.Share{wrongDirectory, wrongSpace, wrongOpaqueSpace, wrongType, wrongHost, wrongTenant, unboundOutgoing} { + if _, err := m.GetShare(ctx, &userpb.User{Id: survivor.Creator}, idRef(survivor.Id)); err != nil { + t.Fatalf("unrelated grant unavailable: %v", err) + } + } + var remainingGroup int64 + if err := m.db.Model(&model.OcmShare{}).Where("id = ?", group.Id.OpaqueId).Count(&remainingGroup).Error; err != nil || remainingGroup != 1 { + t.Fatalf("group grant was changed: count %d: %v", remainingGroup, err) + } + incoming := func(local *userpb.UserId, remote *userpb.UserId, id string) *ocm.ReceivedShare { + t.Helper() + s := grantShare(&userpb.User{Id: local}, remote.Idp, id, file) + s.Creator = remote + return mustStore(t, m, s) + } + chosen := incoming(alice, bob, "001.0") + initial, err := m.GetReceivedShare(ctx, aliceUser, idRef(chosen.Id)) + if err != nil || initial.GetRemoteShareId() != "001.0" || initial.GetGrantee().GetUserId().GetOpaqueId() != "00012" { + t.Fatalf("numeric-looking identities changed on read: %v %v", initial, err) + } + other := incoming(otherDirectory, bob, "incoming-two") + tenantNeighbor := incoming(otherTenant, bob, "incoming-other-tenant") + caseSender := &userpb.UserId{OpaqueId: "BOB", Idp: bob.Idp, Type: bob.Type} + senderNeighbor := incoming(alice, caseSender, "incoming-other-sender") + portNeighbor := incoming(alice, otherHost, "incoming-other-port") + unboundIncoming := incoming(alice, bob, "incoming-unbound") + if err := m.db.Model(&model.OcmReceivedShare{}).Where("id = ?", unboundIncoming.Id.OpaqueId). + Update("recipient_user_type", userpb.UserType_USER_TYPE_INVALID).Error; err != nil { + t.Fatal(err) + } + transfer, err := m.StartReceivedShareTransfer(ctx, aliceUser, chosen, stateMask()) + if err != nil { + t.Fatal(err) + } + declined, err := m.RejectReceivedOCMSharesFromSender(ctx, alice, bob) + if err != nil || len(declined) != 1 || !declined[0].StateChanged() { + t.Fatalf("decline receipts %v: %v", declined, err) + } + got, err := m.GetReceivedShare(ctx, &userpb.User{Id: alice}, idRef(chosen.Id)) + if err != nil || got.State != ocm.ShareState_SHARE_STATE_REJECTED || !got.Hidden { + t.Fatalf("declined share: %v %v", got, err) + } + if _, err := m.GetReceivedShare(ctx, &userpb.User{Id: alice}, idRef(other.Id)); err == nil { + t.Fatal("same opaque ID in another directory was visible") + } + got, err = m.GetReceivedShare(ctx, &userpb.User{Id: otherDirectory}, idRef(other.Id)) + if err != nil || got.State != ocm.ShareState_SHARE_STATE_PENDING { + t.Fatalf("other projection changed: %v %v", got, err) + } + completion, err := m.CompleteReceivedShareTransfer(ctx, aliceUser, chosen.Id, transfer.Generation, ocm.ShareState_SHARE_STATE_ACCEPTED) + if err != nil || completion.StateChanged() { + t.Fatalf("late transfer changed rejected projection: %v %v", completion, err) + } + for _, neighbor := range []struct { + user *userpb.UserId + share *ocm.ReceivedShare + }{{otherTenant, tenantNeighbor}, {alice, portNeighbor}, {alice, senderNeighbor}, {alice, unboundIncoming}} { + got, err := m.GetReceivedShare(ctx, &userpb.User{Id: neighbor.user}, idRef(neighbor.share.Id)) + if err != nil || got.GetState() != ocm.ShareState_SHARE_STATE_PENDING { + t.Fatalf("unrelated projection changed: %v %v", got, err) + } + } + repeated, err := m.RejectReceivedOCMSharesFromSender(ctx, alice, bob) + if err != nil || len(repeated) != 0 { + t.Fatalf("repeat decline receipts %v: %v", repeated, err) + } + chosen.State = ocm.ShareState_SHARE_STATE_ACCEPTED + if _, err := m.UpdateReceivedShare(ctx, &userpb.User{Id: alice}, chosen, &field_mask.FieldMask{Paths: []string{"state"}}); err != nil { + t.Fatalf("explicit reaccept: %v", err) + } + }) +} + +func TestDirectedWithdrawalUnknownCommitObservesCapturedGrant(t *testing.T) { + forEachDialectConfig(t, func(t *testing.T, cfg map[string]any) { + ctx := context.Background() + m := openOCMManager(t, cfg) + writer := openOCMManager(t, cfg) + alice := &userpb.UserId{OpaqueId: "alice", Idp: "directory", Type: userpb.UserType_USER_TYPE_PRIMARY} + bob := &userpb.UserId{OpaqueId: "bob", Idp: "remote.example.org", Type: userpb.UserType_USER_TYPE_FEDERATED} + store := func(manager *mgr, token string) *ocm.Share { + t.Helper() + grantee := &provider.Grantee{Type: provider.GranteeType_GRANTEE_TYPE_USER, Id: &provider.Grantee_UserId{UserId: bob}} + s := getOcmShare(getOcmAccessMethods("viewer"), grantee, alice, getResourceId(), token) + s.RecipientType = ocm.RecipientType_RECIPIENT_TYPE_USER + id, err := manager.GenerateID(ctx) + if err != nil { + t.Fatal(err) + } + s.Id = id + if _, err := manager.StoreShare(ctx, s, file); err != nil { + t.Fatal(err) + } + return s + } + captured := []*ocm.Share{store(m, "captured"), store(m, "captured-duplicate")} + var later *ocm.Share + fault := &commitFault{apply: true, between: func() { later = store(writer, "later") }} + withCommitFault(t, m, fault) + fault.armed.Store(true) + removed, err := m.RemoveOCMSharesForRecipient(ctx, alice, bob) + var unknown *share.CommitUnknownError + if removed != nil || !errors.As(err, &unknown) || unknown.Observed != share.CommitObservedRequested { + t.Fatalf("receipts %v, unknown commit %v", removed, err) + } + owner := &userpb.User{Id: alice} + for _, grant := range captured { + if _, err := writer.GetShare(ctx, owner, idRef(grant.Id)); !errors.Is(err, share.ErrShareNotFound) { + t.Errorf("captured grant %s remains available: %v", grant.Id.OpaqueId, err) + } + } + if later == nil { + t.Fatal("later grant was not stored") + } + if got, err := writer.GetShare(ctx, owner, idRef(later.Id)); err != nil || got.GetToken() != later.Token { + t.Fatalf("uncaptured grant unavailable: %v", err) + } + }) +} + +func TestDirectedDeclineUnknownCommitIgnoresEarlierRejection(t *testing.T) { + forEachDialectConfig(t, func(t *testing.T, cfg map[string]any) { + ctx := context.Background() + m := openOCMManager(t, cfg) + alice := &userpb.UserId{OpaqueId: "alice", Idp: "directory", Type: userpb.UserType_USER_TYPE_PRIMARY} + bob := &userpb.UserId{OpaqueId: "bob", Idp: "remote.example.org", Type: userpb.UserType_USER_TYPE_FEDERATED} + store := func(id string) *ocm.ReceivedShare { + s := grantShare(&userpb.User{Id: alice}, bob.Idp, id, file) + s.Creator = bob + return mustStore(t, m, s) + } + already := store("already-rejected") + already.State = ocm.ShareState_SHARE_STATE_REJECTED + if _, err := m.UpdateReceivedShare(ctx, &userpb.User{Id: alice}, already, &field_mask.FieldMask{Paths: []string{"state"}}); err != nil { + t.Fatal(err) + } + store("pending") + fault := &commitFault{} + withCommitFault(t, m, fault) + fault.armed.Store(true) + receipts, err := m.RejectReceivedOCMSharesFromSender(ctx, alice, bob) + var unknown *share.CommitUnknownError + if receipts != nil || !errors.As(err, &unknown) || unknown.Observed != share.CommitObservedPrevious { + t.Fatalf("receipts %v, unknown commit %v", receipts, err) + } + }) +} + +func TestDirectedDeclineUnknownCommitObservesAppliedGeneration(t *testing.T) { + forEachDialectConfig(t, func(t *testing.T, cfg map[string]any) { + ctx := context.Background() + m := openOCMManager(t, cfg) + reader := openOCMManager(t, cfg) + alice := &userpb.UserId{OpaqueId: "alice", Idp: "directory", Type: userpb.UserType_USER_TYPE_PRIMARY} + bob := &userpb.UserId{OpaqueId: "bob", Idp: "remote.example.org", Type: userpb.UserType_USER_TYPE_FEDERATED} + s := grantShare(&userpb.User{Id: alice}, bob.Idp, "pending", file) + s.Creator = bob + pending := mustStore(t, m, s) + const appliedGeneration = uint64(9) + // Persist a distinct generation to exercise the observer's readback. + if err := m.db.Callback().Update().Before("gorm:update").Register("test:applied-decline-generation", func(tx *gorm.DB) { + fields, ok := tx.Statement.Dest.(map[string]any) + if !ok || fields["transfer_generation"] == nil { + _ = tx.AddError(errors.New("decline did not write a generation")) + return + } + fields["transfer_generation"] = appliedGeneration + }); err != nil { + t.Fatal(err) + } + fault := &commitFault{apply: true} + withCommitFault(t, m, fault) + fault.armed.Store(true) + receipts, err := m.RejectReceivedOCMSharesFromSender(ctx, alice, bob) + row := receivedRow(t, reader, pending.Id.OpaqueId) + if row.State != model.OcmShareStateRejected || !row.Hidden || row.TransferGeneration != appliedGeneration { + t.Fatalf("stored decline state %v, hidden %t, generation %d", row.State, row.Hidden, row.TransferGeneration) + } + var unknown *share.CommitUnknownError + if receipts != nil || !errors.As(err, &unknown) || unknown.Observed != share.CommitObservedRequested { + t.Fatalf("receipts %v, unknown commit %v", receipts, err) + } + }) +} + +func TestEmbeddedPayloadRequiresExactRecipient(t *testing.T) { + forEachDialectConfig(t, func(t *testing.T, cfg map[string]any) { + ctx := context.Background() + m := openOCMManager(t, cfg) + alice := &userpb.User{Id: &userpb.UserId{OpaqueId: "alice", Idp: "directory", Type: userpb.UserType_USER_TYPE_PRIMARY}} + other := &userpb.User{Id: &userpb.UserId{OpaqueId: "alice", Idp: "other", Type: userpb.UserType_USER_TYPE_PRIMARY}} + s := grantShare(alice, "remote.example.org", "embedded", ocm.SharedResourceType_SHARE_RESOURCE_TYPE_EMBEDDED) + s.Protocols = append(s.Protocols, share.NewEmbeddedProtocol(`{"@graph":[]}`)) + stored := mustStore(t, m, s) + if payload, err := m.GetEmbeddedPayload(ctx, other, stored); err == nil || payload != "" { + t.Fatalf("other recipient received payload: %q %v", payload, err) + } + payload, err := m.GetEmbeddedPayload(ctx, alice, stored) + if err != nil { + t.Fatalf("owner payload: %v", err) + } + var decoded map[string][]any + if err := json.Unmarshal([]byte(payload), &decoded); err != nil || len(decoded) != 1 || decoded["@graph"] == nil || len(decoded["@graph"]) != 0 { + t.Fatalf("unexpected owner payload: %q %v", payload, err) + } + }) +} + +func TestOutgoingOptionalBindingPreservesOrdinaryAdmission(t *testing.T) { + forEachDialectConfig(t, func(t *testing.T, cfg map[string]any) { + ctx := context.Background() + m := openOCMManager(t, cfg) + creator := &userpb.UserId{OpaqueId: "alice", Idp: strings.Repeat("d", 1020), Type: userpb.UserType_USER_TYPE_PRIMARY} + remote := &userpb.UserId{OpaqueId: "bob", Idp: "remote.example.org", Type: userpb.UserType_USER_TYPE_FEDERATED} + store := func(c, r *userpb.UserId, token string) (*ocm.Share, error) { + g := &provider.Grantee{Type: provider.GranteeType_GRANTEE_TYPE_USER, Id: &provider.Grantee_UserId{UserId: r}} + s := getOcmShare(getOcmAccessMethods("viewer"), g, c, &provider.ResourceId{StorageId: "storage", OpaqueId: token}, token) + s.RecipientType = ocm.RecipientType_RECIPIENT_TYPE_USER + id, err := m.GenerateID(ctx) + if err != nil { + t.Fatal(err) + } + s.Id = id + return m.StoreShare(ctx, s, file) + } + stored, err := store(creator, remote, "boundary") + if err != nil { + t.Fatal(err) + } + got, err := m.GetShare(ctx, &userpb.User{Id: creator}, idRef(stored.Id)) + if err != nil || got.GetCreator().GetOpaqueId() != creator.OpaqueId || got.GetGrantee().GetUserId().GetOpaqueId() != remote.OpaqueId { + t.Fatalf("identity did not round-trip: %v", err) + } + for _, field := range []string{"idp", "tenant"} { + tooLong := &userpb.UserId{OpaqueId: creator.OpaqueId, Idp: creator.Idp, Type: creator.Type} + if field == "idp" { + tooLong.Idp += "x" + } else { + tooLong.TenantId = strings.Repeat("t", 1021) + } + unbound, err := store(tooLong, remote, field) + if err != nil { + t.Fatalf("ordinary store with overlong %s: %v", field, err) + } + if got, err := m.GetShare(ctx, &userpb.User{Id: tooLong}, idRef(unbound.Id)); err != nil || got.GetToken() != field { + t.Fatalf("ordinary lookup with overlong %s: %v %v", field, got, err) + } + var row model.OcmShare + if err := m.db.First(&row, "id = ?", unbound.Id.OpaqueId).Error; err != nil { + t.Fatal(err) + } + if row.CreatorIdp != nil || row.CreatorTenant != nil || row.RemoteRecipient != nil || row.CreatorUserType != 0 { + t.Fatalf("overlong %s left a partial binding", field) + } + receipts, err := m.RemoveOCMSharesForRecipient(ctx, tooLong, remote) + if err != nil || len(receipts) != 0 { + t.Fatalf("directed withdrawal with overlong %s = %v, %v", field, receipts, err) + } + } + receipts, err := m.RemoveOCMSharesForRecipient(ctx, creator, remote) + if err != nil || len(receipts) != 1 || receipts[0].Share.GetId().GetOpaqueId() != stored.Id.OpaqueId { + t.Fatalf("directed withdrawal with exact representable binding = %v, %v", receipts, err) + } + }) +} + +func TestReceivedInitializationPreservesLegacyMySQLRemoteID(t *testing.T) { + target, ok := mysqlTestTarget(t) + if !ok { + t.Skip("disposable MySQL required") + } + cfg := openMySQLDatabase(t, target) + m := openOCMManager(t, cfg) + alice := recipient("alice") + stored := mustStore(t, m, grantShare(alice, "remote.example.org", "initial", file)) + // Seed a row at the inherited VARCHAR character limit before reopening. + if err := m.db.Exec("ALTER TABLE ocm_received_shares MODIFY remote_share_id VARCHAR(255) CHARACTER SET utf8mb4 NOT NULL").Error; err != nil { + t.Fatal(err) + } + remoteID := strings.Repeat("界", 255) + if err := m.db.Model(&model.OcmReceivedShare{}).Where("id = ?", stored.Id.OpaqueId). + Updates(map[string]any{"remote_share_id": remoteID, "grant_key": nil}).Error; err != nil { + t.Fatal(err) + } + m = openOCMManager(t, cfg) + reopened, err := m.GetReceivedShare(context.Background(), alice, idRef(stored.Id)) + if err != nil || reopened.GetRemoteShareId() != remoteID { + t.Fatalf("legacy remote ID changed on initialization: got %d bytes, error %v", len(reopened.GetRemoteShareId()), err) + } +} + +func TestDirectedWithdrawalRejectsInvalidSelectionAtomically(t *testing.T) { + forEachDialectConfig(t, func(t *testing.T, cfg map[string]any) { + ctx := context.Background() + m := openOCMManager(t, cfg) + alice := &userpb.UserId{OpaqueId: "alice", Idp: "directory", Type: userpb.UserType_USER_TYPE_PRIMARY} + bob := &userpb.UserId{OpaqueId: "bob", Idp: "remote.example.org", Type: userpb.UserType_USER_TYPE_FEDERATED} + ids := make([]*ocm.ShareId, 0, 2) + for _, token := range []string{"first", "second"} { + g := &provider.Grantee{Type: provider.GranteeType_GRANTEE_TYPE_USER, Id: &provider.Grantee_UserId{UserId: bob}} + s := getOcmShare(getOcmAccessMethods("viewer"), g, alice, &provider.ResourceId{StorageId: "storage", OpaqueId: token}, token) + s.RecipientType = ocm.RecipientType_RECIPIENT_TYPE_USER + id, err := m.GenerateID(ctx) + if err != nil { + t.Fatal(err) + } + s.Id = id + if _, err := m.StoreShare(ctx, s, file); err != nil { + t.Fatal(err) + } + ids = append(ids, id) + } + if err := m.db.Model(&model.OcmShare{}).Where("id = ?", ids[1].OpaqueId).Update("item_type", "invalid").Error; err != nil { + t.Fatal(err) + } + if receipts, err := m.RemoveOCMSharesForRecipient(ctx, alice, bob); err == nil || receipts != nil { + t.Fatalf("invalid selection returned receipts %v, error %v", receipts, err) + } + var remaining int64 + if err := m.db.Model(&model.OcmShare{}).Where("id IN ?", []string{ids[0].OpaqueId, ids[1].OpaqueId}).Count(&remaining).Error; err != nil || remaining != 2 { + t.Fatalf("selection was partly withdrawn: %d rows: %v", remaining, err) + } + }) +} + +// Ordinary reads and updates use every part of the stored recipient, its user +// type included. A row without a stored type keeps matching any type. +func TestReceivedShareRequiresExactRecipient(t *testing.T) { + forEachDialect(t, func(t *testing.T, m *mgr) { + ctx := context.Background() + exact := &userpb.UserId{OpaqueId: "00012", Idp: "Directory", TenantId: "Tenant", Type: userpb.UserType_USER_TYPE_PRIMARY} + store := func(remoteID string) *ocm.ReceivedShare { + t.Helper() + s := grantShare(&userpb.User{Id: exact}, "remote.example.org", remoteID, file) + s.Grantee = &provider.Grantee{Type: provider.GranteeType_GRANTEE_TYPE_USER, Id: &provider.Grantee_UserId{UserId: exact}} + return mustStore(t, m, s) + } + typed := store("typed") + untyped := store("untyped") + if err := m.db.Model(&model.OcmReceivedShare{}).Where("id = ?", untyped.Id.OpaqueId).Update("recipient_user_type", 0).Error; err != nil { + t.Fatal(err) + } + accept := func(rs *ocm.ReceivedShare) *ocm.ReceivedShare { + return &ocm.ReceivedShare{Id: rs.Id, State: ocm.ShareState_SHARE_STATE_ACCEPTED} + } + + otherType := &userpb.UserId{OpaqueId: "00012", Idp: "Directory", TenantId: "Tenant", Type: userpb.UserType_USER_TYPE_FEDERATED} + for _, other := range []*userpb.UserId{ + {OpaqueId: "00012 ", Idp: "Directory", TenantId: "Tenant", Type: exact.Type}, + {OpaqueId: "00012", Idp: "directory", TenantId: "Tenant", Type: exact.Type}, + {OpaqueId: "00012", Idp: "Directory", TenantId: "tenant", Type: exact.Type}, + otherType, + } { + u := &userpb.User{Id: other} + if got, err := m.GetReceivedShare(ctx, u, idRef(typed.Id)); !errors.Is(err, share.ErrShareNotFound) { + t.Fatalf("%v read the share: %v %v", other, got, err) + } + if got, err := m.UpdateReceivedShare(ctx, u, accept(typed), stateMask()); !errors.Is(err, share.ErrShareNotFound) { + t.Fatalf("%v updated the share: %v %v", other, got, err) + } + list, err := m.ListReceivedShares(ctx, u, nil) + if err != nil { + t.Fatal(err) + } + for _, rs := range list { + if rs.Id.OpaqueId == typed.Id.OpaqueId { + t.Fatalf("%v listed the share", other) + } + } + } + + owner := &userpb.User{Id: exact} + got, err := m.GetReceivedShare(ctx, owner, idRef(typed.Id)) + if err != nil || got.GetGrantee().GetUserId().GetType() != userpb.UserType_USER_TYPE_PRIMARY { + t.Fatalf("typed readback: %v %v", got, err) + } + if u, err := m.UpdateReceivedShare(ctx, owner, accept(typed), stateMask()); err != nil || !u.StateChanged() { + t.Fatalf("owner update: %v %v", u, err) + } + if u, err := m.UpdateReceivedShare(ctx, &userpb.User{Id: otherType}, accept(untyped), stateMask()); err != nil || !u.StateChanged() { + t.Fatalf("untyped row update: %v %v", u, err) + } + }) +} diff --git a/pkg/share/manager/sql/ocm_directed_concurrency_test.go b/pkg/share/manager/sql/ocm_directed_concurrency_test.go new file mode 100644 index 00000000000..71f0d377d06 --- /dev/null +++ b/pkg/share/manager/sql/ocm_directed_concurrency_test.go @@ -0,0 +1,229 @@ +// Copyright 2026 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. + +package sql + +import ( + "context" + dbsql "database/sql" + "errors" + "sync/atomic" + "testing" + "time" + + userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" + ocm "github.com/cs3org/go-cs3apis/cs3/sharing/ocm/v1beta1" + provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" + "github.com/cs3org/reva/v3/pkg/share/manager/sql/model" + "gorm.io/gorm" +) + +// transactionGate pauses at the actual commit or after an actual rollback. +// It is confined to the action's pool; the other manager uses a separate pool. +type transactionGate struct { + *dbsql.DB + mode string + reached chan struct{} + release chan struct{} + fired atomic.Bool +} +type gatedTx struct { + *dbsql.Tx + gate *transactionGate +} + +func (g *transactionGate) BeginTx(ctx context.Context, opts *dbsql.TxOptions) (gorm.ConnPool, error) { + tx, err := g.DB.BeginTx(ctx, opts) + if err != nil { + return nil, err + } + return &gatedTx{Tx: tx, gate: g}, nil +} +func (t *gatedTx) Commit() error { + if t.gate.mode == "commit" && t.gate.fired.CompareAndSwap(false, true) { + close(t.gate.reached) + <-t.gate.release + } + return t.Tx.Commit() +} +func (t *gatedTx) Rollback() error { + err := t.Tx.Rollback() + if t.gate.mode == "retry" && t.gate.fired.CompareAndSwap(false, true) { + close(t.gate.reached) + <-t.gate.release + } + return err +} + +func TestDirectedTransactionConcurrentSelectionAndRetry(t *testing.T) { + forEachDialectConfig(t, func(t *testing.T, cfg map[string]any) { + for _, direction := range []string{"outgoing", "incoming"} { + for _, mode := range []string{"commit", "retry"} { + t.Run(direction+"/"+mode, func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + m := openOCMManager(t, cfg) + writer := openOCMManager(t, cfg) + alice := &userpb.UserId{OpaqueId: "concurrency-alice-" + direction + "-" + mode, Idp: "directory", Type: userpb.UserType_USER_TYPE_PRIMARY} + bob := &userpb.UserId{OpaqueId: "concurrency-bob", Idp: "remote.example.org", Type: userpb.UserType_USER_TYPE_FEDERATED} + store := func(manager *mgr, token string) (string, error) { + if direction == "incoming" { + s := grantShare(&userpb.User{Id: alice}, bob.Idp, token, file) + s.Creator = bob + got, err := manager.StoreReceivedShare(ctx, s) + if err != nil { + return "", err + } + return got.Id.OpaqueId, nil + } + g := &provider.Grantee{Type: provider.GranteeType_GRANTEE_TYPE_USER, Id: &provider.Grantee_UserId{UserId: bob}} + s := getOcmShare(getOcmAccessMethods("viewer"), g, alice, &provider.ResourceId{StorageId: "storage", OpaqueId: token}, token) + s.RecipientType = ocm.RecipientType_RECIPIENT_TYPE_USER + id, err := manager.GenerateID(ctx) + if err != nil { + return "", err + } + s.Id = id + _, err = manager.StoreShare(ctx, s, file) + return id.OpaqueId, err + } + original, err := store(m, direction+mode+"original") + if err != nil { + t.Fatal(err) + } + db, err := m.db.DB() + if err != nil { + t.Fatal(err) + } + gate := &transactionGate{DB: db, mode: mode, reached: make(chan struct{}), release: make(chan struct{})} + m.db.Statement.ConnPool = gate + var injected atomic.Bool + if mode == "retry" { + callback := func(tx *gorm.DB) { + if injected.CompareAndSwap(false, true) { + tx.AddError(errors.New("database is locked: injected retryable failure after mutation")) + } + } + if direction == "outgoing" { + err = m.db.Callback().Delete().After("gorm:delete").Register("test:retry-directed-delete", callback) + } else { + err = m.db.Callback().Update().After("gorm:update").Register("test:retry-directed-update", callback) + } + if err != nil { + t.Fatal(err) + } + } + type result struct { + ids []string + err error + } + done := make(chan result, 1) + go func() { + var out result + if direction == "outgoing" { + receipts, err := m.RemoveOCMSharesForRecipient(ctx, alice, bob) + out.err = err + for _, receipt := range receipts { + out.ids = append(out.ids, receipt.Share.Id.OpaqueId) + } + } else { + receipts, err := m.RejectReceivedOCMSharesFromSender(ctx, alice, bob) + out.err = err + for _, receipt := range receipts { + out.ids = append(out.ids, receipt.After.Id.OpaqueId) + } + } + done <- out + }() + select { + case <-gate.reached: + case <-ctx.Done(): + t.Fatal("transaction did not reach barrier") + } + type stored struct { + id string + err error + } + added := make(chan stored, 1) + started := make(chan struct{}) + go func() { close(started); id, err := store(writer, direction+mode+"later"); added <- stored{id, err} }() + <-started + if mode == "retry" { + // The first attempt has really rolled back. Make the new + // grant durable before the fresh selection starts. + select { + case s := <-added: + added <- s + if s.err != nil { + close(gate.release) + t.Fatal(s.err) + } + case <-ctx.Done(): + close(gate.release) + t.Fatal("new grant did not commit after rollback") + } + } + close(gate.release) + var action result + select { + case action = <-done: + case <-ctx.Done(): + t.Fatal("action did not complete") + } + var later stored + select { + case later = <-added: + case <-ctx.Done(): + t.Fatal("new grant did not complete") + } + if action.err != nil || later.err != nil { + t.Fatalf("action: %v, writer: %v", action.err, later.err) + } + want := 1 + if mode == "retry" { + want = 2 + } + if len(action.ids) != want { + t.Fatalf("receipts %v; wanted %d", action.ids, want) + } + has := func(id string) bool { + for _, x := range action.ids { + if x == id { + return true + } + } + return false + } + if !has(original) || has(later.id) != (mode == "retry") { + t.Fatalf("selection %v, original %s, later %s", action.ids, original, later.id) + } + if direction == "outgoing" { + var count int64 + if err := writer.db.Model(&model.OcmShare{}).Where("id = ?", later.id).Count(&count).Error; err != nil || (count == 1) != (mode == "commit") { + t.Fatalf("later live rows %d: %v", count, err) + } + } else { + got, err := writer.GetReceivedShare(ctx, &userpb.User{Id: alice}, idRef(&ocm.ShareId{OpaqueId: later.id})) + if err != nil { + t.Fatal(err) + } + expected := ocm.ShareState_SHARE_STATE_PENDING + if mode == "retry" { + expected = ocm.ShareState_SHARE_STATE_REJECTED + } + if got.State != expected { + t.Fatalf("later state %v, expected %v", got.State, expected) + } + } + }) + } + } + }) +} diff --git a/pkg/share/manager/sql/ocm_shares.go b/pkg/share/manager/sql/ocm_shares.go index 04ffc3a4e80..d0290209c77 100644 --- a/pkg/share/manager/sql/ocm_shares.go +++ b/pkg/share/manager/sql/ocm_shares.go @@ -34,6 +34,7 @@ import ( typesv1beta1 "github.com/cs3org/go-cs3apis/cs3/types/v1beta1" "github.com/cs3org/reva/v3/pkg/appctx" "github.com/cs3org/reva/v3/pkg/errtypes" + "github.com/cs3org/reva/v3/pkg/ocm/providerdomain" "github.com/cs3org/reva/v3/pkg/ocm/share" model "github.com/cs3org/reva/v3/pkg/share/manager/sql/model" "github.com/cs3org/reva/v3/pkg/utils/cfg" @@ -106,8 +107,10 @@ func (m *mgr) StoreShare(ctx context.Context, s *ocm.Share, resourceType ocm.Sha return nil, errtypes.BadRequest("invalid share ID") } id := uint(parsed) + creator := s.GetCreator() + grantee := s.GetGrantee().GetUserId() + host, hostErr := providerdomain.CanonicalOCMHost(grantee.GetIdp()) err = m.db.Transaction(func(tx *gorm.DB) error { - share := &model.OcmShare{ Token: s.Token, Instance: s.ResourceId.StorageId, @@ -120,6 +123,15 @@ func (m *mgr) StoreShare(ctx context.Context, s *ocm.Share, resourceType ocm.Sha Mtime: s.Mtime.Seconds, RecipientType: convertFromCS3OCMShareType(s.RecipientType), } + // Optional directed metadata must fit as a complete binding. + if creator.GetIdp() != "" && len(creator.GetIdp()) <= 1020 && len(creator.GetTenantId()) <= 1020 && + creator.GetType() != userpb.UserType_USER_TYPE_INVALID && hostErr == nil && grantee.GetOpaqueId() != "" && + len(grantee.GetOpaqueId())+len(host)+1 <= 1025 { + share.CreatorIdp = []byte(creator.GetIdp()) + share.CreatorUserType = int32(creator.GetType()) + share.CreatorTenant = []byte(creator.GetTenantId()) + share.RemoteRecipient = []byte(grantee.GetOpaqueId() + "@" + host) + } if s.Expiration != nil { share.Expiration = datatypes.NullTime{ V: time.Unix(int64(s.Expiration.Seconds), 0), @@ -281,36 +293,56 @@ func (m *mgr) DeleteShare(ctx context.Context, user *userpb.User, ref *ocm.Share } } - // The soft-delete timestamp participates in the unique key. Matching - // grants need distinct timestamps at MySQL's millisecond precision. - first := matches[0] + return deleteLockedOCMShares(tx, matches, share.ErrShareNotFound) + }) + if err != nil { + return nil, err + } + return removals, nil +} + +// deleteLockedOCMShares soft-deletes only the rows its caller locked and authorized. +func deleteLockedOCMShares(tx *gorm.DB, rows []model.OcmShare, changedErr error) error { + if len(rows) > 1 { + ids := make([]uint, 0, len(rows)) + for _, row := range rows { + ids = append(ids, row.Id) + } + // Database ordering keeps collated variants in the same tuple order. + var ordered []model.OcmShare + if err := forUpdate(tx).Select("id", "instance", "inode", "share_with"). + Where("id IN ?", ids).Order("instance, inode, share_with, id").Find(&ordered).Error; err != nil { + return err + } + if len(ordered) != len(rows) { + return changedErr + } + rows = ordered + } + cutoff := tx.NowFunc().UTC().Truncate(time.Millisecond) + for _, row := range rows { + // The soft-delete timestamp participates in the unique key. Use its + // database equality and millisecond precision to avoid collisions. var latest model.OcmShare if err := forUpdate(tx.Unscoped()).Select("deleted_at"). - Where("instance = ? AND inode = ? AND share_with = ? AND deleted_at IS NOT NULL", first.Instance, first.Inode, first.ShareWith). + Where("instance = ? AND inode = ? AND share_with = ? AND deleted_at IS NOT NULL", row.Instance, row.Inode, row.ShareWith). Order("deleted_at DESC").Limit(1).Find(&latest).Error; err != nil { return err } - deletedAt := tx.NowFunc().UTC().Truncate(time.Millisecond) + deletedAt := cutoff if latest.DeletedAt.Valid && !deletedAt.After(latest.DeletedAt.Time) { deletedAt = latest.DeletedAt.Time.UTC().Truncate(time.Millisecond).Add(time.Millisecond) } - for _, row := range matches { - del := tx.Session(&gorm.Session{NowFunc: func() time.Time { return deletedAt }}) - result := del.Where("id = ?", row.Id).Delete(&model.OcmShare{}) - if result.Error != nil { - return result.Error - } - if result.RowsAffected != 1 { - return share.ErrShareNotFound - } - deletedAt = deletedAt.Add(time.Millisecond) + del := tx.Session(&gorm.Session{NowFunc: func() time.Time { return deletedAt }}) + result := del.Where("id = ?", row.Id).Delete(&model.OcmShare{}) + if result.Error != nil { + return result.Error + } + if result.RowsAffected != 1 { + return changedErr } - return nil - }) - if err != nil { - return nil, err } - return removals, nil + return nil } func accessMethodsTx(tx *gorm.DB, shareID uint) ([]*ocm.AccessMethod, error) { @@ -663,6 +695,9 @@ func (m *mgr) GetReceivedShare(ctx context.Context, user *userpb.User, ref *ocm. // with a grant key binds IdP and tenant, and a blank IdP also binds user type. // Older rows only have the opaque ID. func receivedBy(row *model.OcmReceivedShare, id *userpb.UserId) bool { + if row.RecipientUserType != 0 && row.RecipientUserType != int32(id.GetType()) { + return false + } if id.GetOpaqueId() == "" || row.ShareWith != id.GetOpaqueId() { return false } @@ -738,16 +773,7 @@ func (m *mgr) UpdateReceivedShare(ctx context.Context, user *userpb.User, s *ocm if err != nil { return err } - // A fresh copy per attempt, so a retry never reuses a stale value. - attempt := maps.Clone(updates) - if state, ok := attempt["state"]; ok && state != row.State { - gen, err := nextTransferGeneration(row.TransferGeneration) - if err != nil { - return err - } - attempt["transfer_generation"] = gen - } - if err := tx.Model(&model.OcmReceivedShare{}).Where("id = ?", row.ID).Updates(attempt).Error; err != nil { + if err := updateReceivedFields(tx, row, updates); err != nil { return err } expected, err := readReceivedProjection(tx, row.ID) @@ -768,6 +794,19 @@ func (m *mgr) UpdateReceivedShare(ctx context.Context, user *userpb.User, s *ocm return &receipt, nil } +func updateReceivedFields(tx *gorm.DB, row *model.OcmReceivedShare, updates map[string]any) error { + // A fresh copy per attempt, so a retry never reuses a stale value. + attempt := maps.Clone(updates) + if state, ok := attempt["state"]; ok && state != row.State { + gen, err := nextTransferGeneration(row.TransferGeneration) + if err != nil { + return err + } + attempt["transfer_generation"] = gen + } + return tx.Model(&model.OcmReceivedShare{}).Where("id = ?", row.ID).Updates(attempt).Error +} + // receivedCheck observes one received share against the projections an // attempt captured before and after its change. func receivedCheck(row *model.OcmReceivedShare, expected, previous *receivedProjection) commitCheck { diff --git a/pkg/share/manager/sql/ocm_withdrawal_test.go b/pkg/share/manager/sql/ocm_withdrawal_test.go index 97fb7da4338..6d6d0f91251 100644 --- a/pkg/share/manager/sql/ocm_withdrawal_test.go +++ b/pkg/share/manager/sql/ocm_withdrawal_test.go @@ -49,7 +49,7 @@ func grantShare(to *userpb.User, origin, remoteID string, rt ocm.SharedResourceT Name: "doc", RemoteShareId: remoteID, Grantee: &provider.Grantee{Type: provider.GranteeType_GRANTEE_TYPE_USER, Id: &provider.Grantee_UserId{ - UserId: &userpb.UserId{OpaqueId: to.Id.OpaqueId, Idp: to.Id.Idp, TenantId: to.Id.TenantId}, + UserId: &userpb.UserId{OpaqueId: to.Id.OpaqueId, Idp: to.Id.Idp, TenantId: to.Id.TenantId, Type: to.Id.Type}, }}, // The owner is a different, service-account identity on purpose: it // must never be used as the origin. From 4b92627368452bb57970905424535f503d120b9c Mon Sep 17 00:00:00 2001 From: Mahdi Baghbani Date: Wed, 25 Nov 2026 09:26:36 +0000 Subject: [PATCH 2/8] docs(ocm): add contact share changelog Signed-off-by: Mahdi Baghbani --- changelog/unreleased/ocm-sql-contact-share-actions.md | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 changelog/unreleased/ocm-sql-contact-share-actions.md diff --git a/changelog/unreleased/ocm-sql-contact-share-actions.md b/changelog/unreleased/ocm-sql-contact-share-actions.md new file mode 100644 index 00000000000..9b10e6dda1d --- /dev/null +++ b/changelog/unreleased/ocm-sql-contact-share-actions.md @@ -0,0 +1,6 @@ +Enhancement: add SQL contact share actions + +Withdraw outgoing shares or decline incoming shares bound to an exact +contact pair. Report the affected grants after the SQL commit. + +https://github.com/cs3org/reva/pull/6058 From d96fe23fcfa78696ef94efefa649e231552116b2 Mon Sep 17 00:00:00 2001 From: Mahdi Baghbani Date: Wed, 25 Nov 2026 15:01:29 +0000 Subject: [PATCH 3/8] fix(ocm): harden directed share actions Signed-off-by: Mahdi Baghbani --- .../ocmshareprovider_emit_test.go | 32 +++ pkg/ocm/share/contact.go | 6 +- pkg/share/manager/sql/model/model.go | 4 +- pkg/share/manager/sql/ocm_contact.go | 101 ++++++--- .../manager/sql/ocm_directed_actions_test.go | 208 +++++++++++++++++- .../sql/ocm_directed_concurrency_test.go | 131 ++++++----- pkg/share/manager/sql/ocm_receipts_test.go | 73 +++++- pkg/share/manager/sql/ocm_shares.go | 27 +-- 8 files changed, 463 insertions(+), 119 deletions(-) diff --git a/internal/grpc/services/ocmshareprovider/ocmshareprovider_emit_test.go b/internal/grpc/services/ocmshareprovider/ocmshareprovider_emit_test.go index b5cb156fc18..cbad3b9bdf4 100644 --- a/internal/grpc/services/ocmshareprovider/ocmshareprovider_emit_test.go +++ b/internal/grpc/services/ocmshareprovider/ocmshareprovider_emit_test.go @@ -778,6 +778,38 @@ func TestEmbeddedAcceptanceNeedsCompletedCopy(t *testing.T) { requireNotices(t, e.peer, ocmd.NotificationShareAccepted) } +func TestDirectedDeclineRefusesServiceCopyUntilCompletion(t *testing.T) { + e := newEmitEnv(t) + recipient := appctx.ContextMustGetUser(e.recip).Id + recipient.Type = userpb.UserType_USER_TYPE_PRIMARY + rs := e.received(t, "directed-copy", true) + sender := &userpb.UserId{OpaqueId: "alice", Idp: e.peer.host()} + actions := e.repo.(share.DirectedShareActions) + + if res := e.setState(t, rs.Id, ocm.ShareState_SHARE_STATE_ACCEPTED, "/home/dest"); res.Status.Code != rpc.Code_CODE_OK { + t.Fatalf("start: %v", res.Status) + } + updates, err := actions.RejectReceivedOCMSharesFromSender(e.recip, recipient, sender) + if updates != nil || !errors.Is(err, share.ErrTransferInProgress) { + t.Fatalf("directed decline returned %d receipts and %v", len(updates), err) + } + if res := e.setState(t, rs.Id, ocm.ShareState_SHARE_STATE_ACCEPTED, "/home/dest"); res.Status.Code != rpc.Code_CODE_FAILED_PRECONDITION { + t.Fatalf("second start: %v", res.Status) + } + if len(e.xfer.callbacks) != 1 { + t.Fatalf("started %d copies", len(e.xfer.callbacks)) + } + requireNotices(t, e.peer) + e.xfer.callback(0)(nil) + requireNotices(t, e.peer, ocmd.NotificationShareAccepted) + + updates, err = actions.RejectReceivedOCMSharesFromSender(e.recip, recipient, sender) + if err != nil || len(updates) != 1 || updates[0].Before.GetState() != ocm.ShareState_SHARE_STATE_ACCEPTED || + updates[0].After.GetState() != ocm.ShareState_SHARE_STATE_REJECTED { + t.Fatalf("directed decline after completion returned %d receipts and %v", len(updates), err) + } +} + func TestSenderFailureKeepsCommittedChange(t *testing.T) { e := newEmitEnv(t) e.peer.status = http.StatusInternalServerError diff --git a/pkg/ocm/share/contact.go b/pkg/ocm/share/contact.go index db971a43c57..ce2e9edd8cd 100644 --- a/pkg/ocm/share/contact.go +++ b/pkg/ocm/share/contact.go @@ -26,8 +26,10 @@ import ( // DirectedShareActions is the transactional bulk surface of a repository: // withdraw exact bound outgoing grants and reject exact bound received grants. -// Each direction either commits its whole captured selection or reports an -// error without an acknowledged receipt. +// Historical grants without a complete binding remain available to ordinary +// per-share operations. Receipts cover only the eligible captured grants. +// Each direction commits the whole selection or returns an error without a +// receipt. A received selection with a transfer in progress is refused. type DirectedShareActions interface { RemoveOCMSharesForRecipient(ctx context.Context, creator, recipient *userpb.UserId) ([]*ShareRemoval, error) RejectReceivedOCMSharesFromSender(ctx context.Context, recipient, sender *userpb.UserId) ([]*ReceivedShareUpdate, error) diff --git a/pkg/share/manager/sql/model/model.go b/pkg/share/manager/sql/model/model.go index d85fd11e786..327e1ad59f1 100644 --- a/pkg/share/manager/sql/model/model.go +++ b/pkg/share/manager/sql/model/model.go @@ -212,10 +212,10 @@ type ShareState struct { // In addition, tokens must be unique. // TODO(lopresti) see if we can consolidate Owner and Initiator with UIDOwner and UIDInitiator in ProtoShare type OcmShare struct { - CreatorIdp []byte `gorm:"type:varbinary(1020);index:i_ocmshare_directed,priority:1"` + CreatorIdp []byte `gorm:"type:varbinary(1020)"` CreatorUserType int32 `gorm:"not null;default:0"` CreatorTenant []byte `gorm:"type:varbinary(1020)"` - RemoteRecipient []byte `gorm:"type:varbinary(1025);index:i_ocmshare_directed,priority:2"` + RemoteRecipient []byte `gorm:"type:varbinary(1025);index:i_ocmshare_remote_recipient"` ProtoShare DeletedAt gorm.DeletedAt `gorm:"uniqueIndex:u_ocmshare"` // the composite index also works as regular index here, similarly as in the `Share` struct Inode string `gorm:"size:64;not null;uniqueIndex:u_ocmshare;index"` diff --git a/pkg/share/manager/sql/ocm_contact.go b/pkg/share/manager/sql/ocm_contact.go index d9a8dc5cfb9..109e81313ab 100644 --- a/pkg/share/manager/sql/ocm_contact.go +++ b/pkg/share/manager/sql/ocm_contact.go @@ -18,12 +18,8 @@ package sql -// Directed bulk share actions. Each direction captures its exact selection -// inside one transaction and either commits all of it or returns without an -// acknowledged receipt. Grants created outside the captured set are later -// separate shares; no pair-wide authority is recorded here. - import ( + "cmp" "context" "slices" "time" @@ -37,6 +33,8 @@ import ( "gorm.io/gorm" ) +const directedObservationBatchSize = 500 + // RemoveOCMSharesForRecipient uses the bound creator identity, including tenant, // because a resource owner or a same-opaque principal may be a different user. func (m *mgr) RemoveOCMSharesForRecipient(ctx context.Context, creator, recipient *userpb.UserId) ([]*share.ShareRemoval, error) { @@ -55,16 +53,12 @@ func (m *mgr) RemoveOCMSharesForRecipient(ctx context.Context, creator, recipien q := forUpdate(tx). Where("creator_idp = ? AND remote_recipient = ? AND initiator = ? AND creator_user_type = ? AND creator_tenant = ? AND recipient_type = ?", []byte(creator.GetIdp()), []byte(recipient.GetOpaqueId()+"@"+remoteHost), creator.GetOpaqueId(), int32(creator.GetType()), []byte(creator.GetTenantId()), model.OcmShareTypeUser). - Order("id") + Order(outgoingShareOrder) var selected []model.OcmShare if err := q.Find(&selected).Error; err != nil { return err } - if len(selected) == 0 { - return nil - } - ids := make([]uint, 0, len(selected)) - authorized := make([]model.OcmShare, 0, len(selected)) + authorized := selected[:0] for _, sm := range selected { // MySQL may collate the ordinary initiator column non-binarily. if sm.Initiator != creator.GetOpaqueId() { @@ -73,23 +67,40 @@ func (m *mgr) RemoveOCMSharesForRecipient(ctx context.Context, creator, recipien if !share.SupportedResourceType(convertToCS3SharedResourceType(sm.ItemType)) { return share.ErrInvalidResourceType } - ids = append(ids, sm.Id) authorized = append(authorized, sm) - methods, err := accessMethodsTx(tx, sm.Id) - if err != nil { - return err - } - receipts = append(receipts, &share.ShareRemoval{Share: convertToCS3OCMShare(&sm, methods), ResourceType: convertToCS3SharedResourceType(sm.ItemType)}) } - if len(ids) == 0 { + if len(authorized) == 0 { return nil } if err := deleteLockedOCMShares(tx, authorized, errtypes.Conflict("selected share changed")); err != nil { return err } + + // Preserve ID order in the receipt after using database order to delete. + slices.SortFunc(authorized, func(a, b model.OcmShare) int { return cmp.Compare(a.Id, b.Id) }) + ids := make([]uint, 0, len(authorized)) + for i := range authorized { + sm := &authorized[i] + methods, err := accessMethodsTx(tx, sm.Id) + if err != nil { + return err + } + ids = append(ids, sm.Id) + receipts = append(receipts, &share.ShareRemoval{Share: convertToCS3OCMShare(sm, methods), ResourceType: convertToCS3SharedResourceType(sm.ItemType)}) + } check.observe = func(db *gorm.DB) (share.CommitObservation, error) { var active int64 - if err := db.Model(&model.OcmShare{}).Where("id IN ?", ids).Count(&active).Error; err != nil { + err := observeTx(db, func(tx *gorm.DB) error { + for chunk := range slices.Chunk(ids, directedObservationBatchSize) { + var count int64 + if err := tx.Model(&model.OcmShare{}).Where("id IN ?", chunk).Count(&count).Error; err != nil { + return err + } + active += count + } + return nil + }) + if err != nil { return share.CommitObservedUnread, err } if active == 0 { @@ -128,17 +139,8 @@ func (m *mgr) RejectReceivedOCMSharesFromSender(ctx context.Context, recipient, Order("id").Find(&selected).Error; err != nil { return err } - if len(selected) == 0 { - return nil - } - type stateSnapshot struct { - State model.OcmShareState - Hidden bool - TransferGeneration uint64 - } - ids := make([]uint, 0, len(selected)) - previous := make([]stateSnapshot, 0, len(selected)) - expected := make([]stateSnapshot, 0, len(selected)) + authorized := selected[:0] + transferring := false for _, row := range selected { if row.Initiator != senderAddress || row.ShareWith != recipient.GetOpaqueId() || row.ShareWithIdp != recipient.GetIdp() || row.ShareWithTenant != recipient.GetTenantId() { @@ -152,6 +154,27 @@ func (m *mgr) RejectReceivedOCMSharesFromSender(ctx context.Context, recipient, if !share.SupportedResourceType(convertToCS3SharedResourceType(row.ItemType)) { return share.ErrInvalidResourceType } + authorized = append(authorized, row) + transferring = transferring || row.State == model.OcmShareStateTransferring + } + // Keep the transfer state while the copy runs so a second accept + // cannot start another copy. + if transferring { + return share.ErrTransferInProgress + } + if len(authorized) == 0 { + return nil + } + + type stateSnapshot struct { + State model.OcmShareState + Hidden bool + TransferGeneration uint64 + } + ids := make([]uint, 0, len(authorized)) + previous := make([]stateSnapshot, 0, len(authorized)) + expected := make([]stateSnapshot, 0, len(authorized)) + for _, row := range authorized { protocols, err := protocolsTx(tx, row.ID) if err != nil { return err @@ -179,13 +202,21 @@ func (m *mgr) RejectReceivedOCMSharesFromSender(ctx context.Context, recipient, expected = append(expected, stateSnapshot{applied.row.State, applied.row.Hidden, applied.row.TransferGeneration}) receipts = append(receipts, &share.ReceivedShareUpdate{Before: before, After: after}) } - if len(ids) == 0 { - return nil - } check.observe = func(db *gorm.DB) (share.CommitObservation, error) { var observed []stateSnapshot - err := db.Model(&model.OcmReceivedShare{}).Select("state", "hidden", "transfer_generation"). - Where("id IN ?", ids).Order("id").Find(&observed).Error + err := observeTx(db, func(tx *gorm.DB) error { + // The captured IDs are already in ascending order. + for chunk := range slices.Chunk(ids, directedObservationBatchSize) { + var states []stateSnapshot + err := tx.Model(&model.OcmReceivedShare{}).Select("state", "hidden", "transfer_generation"). + Where("id IN ?", chunk).Order("id").Find(&states).Error + if err != nil { + return err + } + observed = append(observed, states...) + } + return nil + }) if err != nil { return share.CommitObservedUnread, err } diff --git a/pkg/share/manager/sql/ocm_directed_actions_test.go b/pkg/share/manager/sql/ocm_directed_actions_test.go index 5d8e630635c..42f61024685 100644 --- a/pkg/share/manager/sql/ocm_directed_actions_test.go +++ b/pkg/share/manager/sql/ocm_directed_actions_test.go @@ -18,6 +18,7 @@ import ( "context" "encoding/json" "errors" + "fmt" "strings" "testing" "time" @@ -27,6 +28,7 @@ import ( provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" "github.com/cs3org/reva/v3/pkg/ocm/share" "github.com/cs3org/reva/v3/pkg/share/manager/sql/model" + "github.com/mattn/go-sqlite3" "google.golang.org/genproto/protobuf/field_mask" "gorm.io/gorm" ) @@ -169,6 +171,9 @@ func TestDirectedActionsRespectExactIdentities(t *testing.T) { tenantNeighbor := incoming(otherTenant, bob, "incoming-other-tenant") caseSender := &userpb.UserId{OpaqueId: "BOB", Idp: bob.Idp, Type: bob.Type} senderNeighbor := incoming(alice, caseSender, "incoming-other-sender") + if _, err := m.StartReceivedShareTransfer(ctx, aliceUser, senderNeighbor, stateMask()); err != nil { + t.Fatal(err) + } portNeighbor := incoming(alice, otherHost, "incoming-other-port") unboundIncoming := incoming(alice, bob, "incoming-unbound") if err := m.db.Model(&model.OcmReceivedShare{}).Where("id = ?", unboundIncoming.Id.OpaqueId). @@ -179,6 +184,10 @@ func TestDirectedActionsRespectExactIdentities(t *testing.T) { if err != nil { t.Fatal(err) } + completed, err := m.CompleteReceivedShareTransfer(ctx, aliceUser, chosen.Id, transfer.Generation, ocm.ShareState_SHARE_STATE_ACCEPTED) + if err != nil || !completed.StateChanged() { + t.Fatalf("complete before directed decline: %v %v", completed, err) + } declined, err := m.RejectReceivedOCMSharesFromSender(ctx, alice, bob) if err != nil || len(declined) != 1 || !declined[0].StateChanged() { t.Fatalf("decline receipts %v: %v", declined, err) @@ -201,12 +210,16 @@ func TestDirectedActionsRespectExactIdentities(t *testing.T) { for _, neighbor := range []struct { user *userpb.UserId share *ocm.ReceivedShare - }{{otherTenant, tenantNeighbor}, {alice, portNeighbor}, {alice, senderNeighbor}, {alice, unboundIncoming}} { + }{{otherTenant, tenantNeighbor}, {alice, portNeighbor}, {alice, unboundIncoming}} { got, err := m.GetReceivedShare(ctx, &userpb.User{Id: neighbor.user}, idRef(neighbor.share.Id)) if err != nil || got.GetState() != ocm.ShareState_SHARE_STATE_PENDING { t.Fatalf("unrelated projection changed: %v %v", got, err) } } + got, err = m.GetReceivedShare(ctx, aliceUser, idRef(senderNeighbor.Id)) + if err != nil || got.GetState() != ocm.ShareState_SHARE_STATE_TRANSFERRING { + t.Fatalf("copy belonging to a case-distinct sender changed: %v %v", got, err) + } repeated, err := m.RejectReceivedOCMSharesFromSender(ctx, alice, bob) if err != nil || len(repeated) != 0 { t.Fatalf("repeat decline receipts %v: %v", repeated, err) @@ -218,6 +231,179 @@ func TestDirectedActionsRespectExactIdentities(t *testing.T) { }) } +func TestDirectedDeclineRefusesLiveTransfer(t *testing.T) { + forEachDialect(t, func(t *testing.T, m *mgr) { + ctx := context.Background() + alice := recipient("alice") + bob := &userpb.UserId{OpaqueId: "bob", Idp: "remote.example.org", Type: userpb.UserType_USER_TYPE_FEDERATED} + pending := grantShare(alice, bob.Idp, "pending", file) + pending.Creator = bob + pending = mustStore(t, m, pending) + copying := grantShare(alice, bob.Idp, "copying", ocm.SharedResourceType_SHARE_RESOURCE_TYPE_EMBEDDED) + copying.Creator = bob + copying.Protocols = append(copying.Protocols, share.NewEmbeddedProtocol(`{"@graph":[]}`)) + copying = mustStore(t, m, copying) + transfer, err := m.StartReceivedShareTransfer(ctx, alice, copying, stateMask()) + if err != nil { + t.Fatal(err) + } + + updates, err := m.RejectReceivedOCMSharesFromSender(ctx, alice.Id, bob) + if updates != nil || !errors.Is(err, share.ErrTransferInProgress) { + t.Fatalf("directed decline returned %d receipts and %v", len(updates), err) + } + if got := receivedRow(t, m, pending.Id.OpaqueId); got.State != model.OcmShareStatePending || got.Hidden { + t.Fatalf("pending grant changed: state %v, hidden %t", got.State, got.Hidden) + } + if got := receivedRow(t, m, copying.Id.OpaqueId); got.State != model.OcmShareStateTransferring || + got.Hidden || got.TransferGeneration != transfer.Generation { + t.Fatalf("copy reservation changed: state %v, hidden %t, generation %d", got.State, got.Hidden, got.TransferGeneration) + } + if _, err := m.StartReceivedShareTransfer(ctx, alice, copying, stateMask()); !errors.Is(err, share.ErrTransferInProgress) { + t.Fatalf("second transfer start: %v", err) + } + completion, err := m.CompleteReceivedShareTransfer(ctx, alice, copying.Id, transfer.Generation, ocm.ShareState_SHARE_STATE_ACCEPTED) + if err != nil || !completion.StateChanged() { + t.Fatalf("complete original transfer: %v, %v", completion, err) + } + updates, err = m.RejectReceivedOCMSharesFromSender(ctx, alice.Id, bob) + if err != nil || len(updates) != 2 || + updates[0].After.GetId().GetOpaqueId() != pending.Id.OpaqueId || + updates[1].After.GetId().GetOpaqueId() != copying.Id.OpaqueId { + t.Fatalf("explicit decline after completion: %v, %v", updates, err) + } + for _, update := range updates { + if !update.StateChanged() || !update.After.GetHidden() || update.After.GetState() != ocm.ShareState_SHARE_STATE_REJECTED { + t.Fatalf("invalid decline receipt: %v", update) + } + } + }) +} + +func TestDirectedDeclineRefusesCorruptBinding(t *testing.T) { + forEachDialect(t, func(t *testing.T, m *mgr) { + ctx := context.Background() + alice := recipient("alice") + bob := &userpb.UserId{OpaqueId: "bob", Idp: "remote.example.org"} + for _, id := range []string{"valid", "corrupt"} { + rs := grantShare(alice, bob.Idp, id, file) + rs.Creator = bob + mustStore(t, m, rs) + } + if err := m.db.Model(&model.OcmReceivedShare{}).Where("remote_share_id = ?", "corrupt"). + Update("grant_key", strings.Repeat("0", 64)).Error; err != nil { + t.Fatal(err) + } + updates, err := m.RejectReceivedOCMSharesFromSender(ctx, alice.Id, bob) + if updates != nil || !errors.Is(err, share.ErrGrantIdentityMismatch) { + t.Fatalf("directed decline of corrupt selection: %d receipts, %v", len(updates), err) + } + var pending int64 + if err := m.db.Model(&model.OcmReceivedShare{}).Where("state = ? AND hidden = ?", model.OcmShareStatePending, false). + Count(&pending).Error; err != nil || pending != 2 { + t.Fatalf("pending projections after refusal: %d, %v", pending, err) + } + }) +} + +func TestDirectedBatchesAcrossBindBoundary(t *testing.T) { + const limit = 500 + for _, direction := range []string{"outgoing", "incoming"} { + t.Run(direction, func(t *testing.T) { + forEachDialect(t, func(t *testing.T, m *mgr) { + ctx := context.Background() + sqlite := m.db.Dialector.Name() == "sqlite" + if !sqlite && direction == "incoming" { + t.Skip("SQLite enforces the reduced query limit") + } + cutoff := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + m.db = m.db.Session(&gorm.Session{NowFunc: func() time.Time { return cutoff }}) + alice := recipient("alice") + bob := &userpb.UserId{OpaqueId: "bob", Idp: "remote.example.org", Type: userpb.UserType_USER_TYPE_FEDERATED} + for i := range limit + 1 { + token := fmt.Sprintf("grant-%d", i) + if direction == "incoming" { + s := grantShare(alice, bob.Idp, token, file) + s.Creator = bob + mustStore(t, m, s) + continue + } + grantee := &provider.Grantee{Type: provider.GranteeType_GRANTEE_TYPE_USER, Id: &provider.Grantee_UserId{UserId: bob}} + resource := token + switch i { + case 0: + resource = "same-resource" + case limit: + resource = "same-resource" + if !sqlite { + resource = "SAME-resource" + } + } + s := getOcmShare(nil, grantee, alice.Id, &provider.ResourceId{StorageId: "storage", OpaqueId: resource}, token) + s.RecipientType = ocm.RecipientType_RECIPIENT_TYPE_USER + id, err := m.GenerateID(ctx) + if err != nil { + t.Fatal(err) + } + s.Id = id + if _, err := m.StoreShare(ctx, s, file); err != nil { + t.Fatal(err) + } + } + fault := &commitFault{apply: true} + withCommitFault(t, m, fault) + if sqlite { + fault.DB.SetMaxOpenConns(1) + conn, err := fault.DB.Conn(ctx) + if err != nil { + t.Fatal(err) + } + if err := conn.Raw(func(driverConn any) error { + driverConn.(*sqlite3.SQLiteConn).SetLimit(sqlite3.SQLITE_LIMIT_VARIABLE_NUMBER, limit) + return nil + }); err != nil { + t.Fatal(err) + } + if err := conn.Close(); err != nil { + t.Fatal(err) + } + } + fault.armed.Store(true) + var err error + if direction == "incoming" { + receipts, actionErr := m.RejectReceivedOCMSharesFromSender(ctx, alice.Id, bob) + err = actionErr + if receipts != nil { + t.Fatalf("unknown commit returned %d incoming receipts", len(receipts)) + } + } else { + receipts, actionErr := m.RemoveOCMSharesForRecipient(ctx, alice.Id, bob) + err = actionErr + if receipts != nil { + t.Fatalf("unknown commit returned %d outgoing receipts", len(receipts)) + } + } + var unknown *share.CommitUnknownError + if !errors.As(err, &unknown) || unknown.Observed != share.CommitObservedRequested || fault.reads.Load() != 2 { + t.Fatalf("got %v after %d observation reads, want requested state after two bounded reads", err, fault.reads.Load()) + } + if direction == "outgoing" { + for i, token := range []string{"grant-0", fmt.Sprintf("grant-%d", limit)} { + var row model.OcmShare + if err := m.db.Unscoped().Where("token = ?", token).Take(&row).Error; err != nil { + t.Fatal(err) + } + wantTime := cutoff.Add(time.Duration(i) * time.Millisecond) + if !row.DeletedAt.Valid || !row.DeletedAt.Time.Equal(wantTime) { + t.Fatalf("collated tuple %q deleted at %v, want %v", row.Inode, row.DeletedAt, wantTime) + } + } + } + }) + }) + } +} + func TestDirectedWithdrawalUnknownCommitObservesCapturedGrant(t *testing.T) { forEachDialectConfig(t, func(t *testing.T, cfg map[string]any) { ctx := context.Background() @@ -357,8 +543,14 @@ func TestOutgoingOptionalBindingPreservesOrdinaryAdmission(t *testing.T) { forEachDialectConfig(t, func(t *testing.T, cfg map[string]any) { ctx := context.Background() m := openOCMManager(t, cfg) - creator := &userpb.UserId{OpaqueId: "alice", Idp: strings.Repeat("d", 1020), Type: userpb.UserType_USER_TYPE_PRIMARY} - remote := &userpb.UserId{OpaqueId: "bob", Idp: "remote.example.org", Type: userpb.UserType_USER_TYPE_FEDERATED} + creator := &userpb.UserId{ + OpaqueId: "alice", Idp: strings.Repeat("d", 1020), + TenantId: strings.Repeat("t", 1020), Type: userpb.UserType_USER_TYPE_PRIMARY, + } + const host = "remote.example.org" + remote := &userpb.UserId{ + OpaqueId: strings.Repeat("𐍈", 255-1-len(host)), Idp: host, Type: userpb.UserType_USER_TYPE_FEDERATED, + } store := func(c, r *userpb.UserId, token string) (*ocm.Share, error) { g := &provider.Grantee{Type: provider.GranteeType_GRANTEE_TYPE_USER, Id: &provider.Grantee_UserId{UserId: r}} s := getOcmShare(getOcmAccessMethods("viewer"), g, c, &provider.ResourceId{StorageId: "storage", OpaqueId: token}, token) @@ -378,8 +570,16 @@ func TestOutgoingOptionalBindingPreservesOrdinaryAdmission(t *testing.T) { if err != nil || got.GetCreator().GetOpaqueId() != creator.OpaqueId || got.GetGrantee().GetUserId().GetOpaqueId() != remote.OpaqueId { t.Fatalf("identity did not round-trip: %v", err) } + var bound model.OcmShare + if err := m.db.First(&bound, "id = ?", stored.Id.OpaqueId).Error; err != nil { + t.Fatal(err) + } + if string(bound.CreatorIdp) != creator.Idp || string(bound.CreatorTenant) != creator.TenantId || + string(bound.RemoteRecipient) != remote.OpaqueId+"@"+host { + t.Fatal("upper-width binding changed") + } for _, field := range []string{"idp", "tenant"} { - tooLong := &userpb.UserId{OpaqueId: creator.OpaqueId, Idp: creator.Idp, Type: creator.Type} + tooLong := &userpb.UserId{OpaqueId: creator.OpaqueId, Idp: creator.Idp, TenantId: creator.TenantId, Type: creator.Type} if field == "idp" { tooLong.Idp += "x" } else { diff --git a/pkg/share/manager/sql/ocm_directed_concurrency_test.go b/pkg/share/manager/sql/ocm_directed_concurrency_test.go index 71f0d377d06..9f1cc3d523d 100644 --- a/pkg/share/manager/sql/ocm_directed_concurrency_test.go +++ b/pkg/share/manager/sql/ocm_directed_concurrency_test.go @@ -14,6 +14,8 @@ import ( "context" dbsql "database/sql" "errors" + "slices" + "sync" "sync/atomic" "testing" "time" @@ -22,6 +24,8 @@ import ( ocm "github.com/cs3org/go-cs3apis/cs3/sharing/ocm/v1beta1" provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" "github.com/cs3org/reva/v3/pkg/share/manager/sql/model" + "github.com/go-sql-driver/mysql" + "github.com/mattn/go-sqlite3" "gorm.io/gorm" ) @@ -73,7 +77,7 @@ func TestDirectedTransactionConcurrentSelectionAndRetry(t *testing.T) { writer := openOCMManager(t, cfg) alice := &userpb.UserId{OpaqueId: "concurrency-alice-" + direction + "-" + mode, Idp: "directory", Type: userpb.UserType_USER_TYPE_PRIMARY} bob := &userpb.UserId{OpaqueId: "concurrency-bob", Idp: "remote.example.org", Type: userpb.UserType_USER_TYPE_FEDERATED} - store := func(manager *mgr, token string) (string, error) { + store := func(manager *mgr, token string, id *ocm.ShareId) (string, error) { if direction == "incoming" { s := grantShare(&userpb.User{Id: alice}, bob.Idp, token, file) s.Creator = bob @@ -86,15 +90,18 @@ func TestDirectedTransactionConcurrentSelectionAndRetry(t *testing.T) { g := &provider.Grantee{Type: provider.GranteeType_GRANTEE_TYPE_USER, Id: &provider.Grantee_UserId{UserId: bob}} s := getOcmShare(getOcmAccessMethods("viewer"), g, alice, &provider.ResourceId{StorageId: "storage", OpaqueId: token}, token) s.RecipientType = ocm.RecipientType_RECIPIENT_TYPE_USER - id, err := manager.GenerateID(ctx) - if err != nil { - return "", err + if id == nil { + var err error + id, err = manager.GenerateID(ctx) + if err != nil { + return "", err + } } s.Id = id - _, err = manager.StoreShare(ctx, s, file) + _, err := manager.StoreShare(ctx, s, file) return id.OpaqueId, err } - original, err := store(m, direction+mode+"original") + original, err := store(m, direction+mode+"original", nil) if err != nil { t.Fatal(err) } @@ -103,7 +110,31 @@ func TestDirectedTransactionConcurrentSelectionAndRetry(t *testing.T) { t.Fatal(err) } gate := &transactionGate{DB: db, mode: mode, reached: make(chan struct{}), release: make(chan struct{})} + release := sync.OnceFunc(func() { close(gate.release) }) + defer release() m.db.Statement.ConnPool = gate + var laterID *ocm.ShareId + sqlite := cfg["db_engine"] == "sqlite" + if mode == "commit" { + if direction == "outgoing" { + laterID, err = writer.GenerateID(ctx) + if err != nil { + t.Fatal(err) + } + } + pool, err := writer.db.DB() + if err != nil { + t.Fatal(err) + } + pool.SetMaxOpenConns(1) + setTimeout := "SET SESSION innodb_lock_wait_timeout = 1" + if sqlite { + setTimeout = "PRAGMA busy_timeout = 0" + } + if _, err := pool.ExecContext(ctx, setTimeout); err != nil { + t.Fatal(err) + } + } var injected atomic.Bool if mode == "retry" { callback := func(tx *gorm.DB) { @@ -147,70 +178,64 @@ func TestDirectedTransactionConcurrentSelectionAndRetry(t *testing.T) { case <-ctx.Done(): t.Fatal("transaction did not reach barrier") } - type stored struct { - id string - err error - } - added := make(chan stored, 1) - started := make(chan struct{}) - go func() { close(started); id, err := store(writer, direction+mode+"later"); added <- stored{id, err} }() - <-started - if mode == "retry" { - // The first attempt has really rolled back. Make the new - // grant durable before the fresh selection starts. - select { - case s := <-added: - added <- s - if s.err != nil { - close(gate.release) - t.Fatal(s.err) + token := direction + mode + "later" + if mode == "commit" { + // The action cannot commit until a real competing write + // has been refused by the database. + _, lockErr := store(writer, token, laterID) + var sqliteErr sqlite3.Error + var mysqlErr *mysql.MySQLError + if sqlite { + if !errors.As(lockErr, &sqliteErr) || sqliteErr.Code != sqlite3.ErrBusy { + t.Fatalf("competing store during SQLite transaction: %v, want SQLITE_BUSY", lockErr) } - case <-ctx.Done(): - close(gate.release) - t.Fatal("new grant did not commit after rollback") + } else if !errors.As(lockErr, &mysqlErr) || mysqlErr.Number != 1205 { + t.Fatalf("competing store during InnoDB transaction: %v, want lock wait timeout", lockErr) } + t.Logf("competing %s store reported lock contention before commit", direction) + release() + } + var later string + var writerErr error + if mode == "retry" { + // The first attempt has rolled back. Commit the new + // grant before the action can select again. + later, writerErr = store(writer, token, nil) + release() } - close(gate.release) var action result select { case action = <-done: case <-ctx.Done(): t.Fatal("action did not complete") } - var later stored - select { - case later = <-added: - case <-ctx.Done(): - t.Fatal("new grant did not complete") + if mode == "commit" { + later, writerErr = store(writer, token, laterID) } - if action.err != nil || later.err != nil { - t.Fatalf("action: %v, writer: %v", action.err, later.err) + if action.err != nil || writerErr != nil { + t.Fatalf("action: %v, writer: %v", action.err, writerErr) } - want := 1 + want := []string{original} if mode == "retry" { - want = 2 + want = append(want, later) } - if len(action.ids) != want { - t.Fatalf("receipts %v; wanted %d", action.ids, want) - } - has := func(id string) bool { - for _, x := range action.ids { - if x == id { - return true - } - } - return false - } - if !has(original) || has(later.id) != (mode == "retry") { - t.Fatalf("selection %v, original %s, later %s", action.ids, original, later.id) + if !slices.Equal(action.ids, want) { + t.Fatalf("receipts %v, want %v", action.ids, want) } if direction == "outgoing" { - var count int64 - if err := writer.db.Model(&model.OcmShare{}).Where("id = ?", later.id).Count(&count).Error; err != nil || (count == 1) != (mode == "commit") { - t.Fatalf("later live rows %d: %v", count, err) + var current []model.OcmShare + if err := writer.db.Where("id IN ?", []string{original, later}).Find(¤t).Error; err != nil { + t.Fatal(err) + } + if mode == "commit" && (len(current) != 1 || current[0].Token != token) || + mode == "retry" && len(current) != 0 { + t.Fatalf("unexpected live grants after %s: %d", mode, len(current)) } } else { - got, err := writer.GetReceivedShare(ctx, &userpb.User{Id: alice}, idRef(&ocm.ShareId{OpaqueId: later.id})) + if first := receivedRow(t, writer, original); first.State != model.OcmShareStateRejected || !first.Hidden { + t.Fatal("original incoming grant was not declined") + } + got, err := writer.GetReceivedShare(ctx, &userpb.User{Id: alice}, idRef(&ocm.ShareId{OpaqueId: later})) if err != nil { t.Fatal(err) } diff --git a/pkg/share/manager/sql/ocm_receipts_test.go b/pkg/share/manager/sql/ocm_receipts_test.go index 7732f08b9f8..44fe5b8b449 100644 --- a/pkg/share/manager/sql/ocm_receipts_test.go +++ b/pkg/share/manager/sql/ocm_receipts_test.go @@ -36,6 +36,8 @@ import ( "github.com/cs3org/reva/v3/pkg/ocm/share" "github.com/cs3org/reva/v3/pkg/permissions" model "github.com/cs3org/reva/v3/pkg/share/manager/sql/model" + "github.com/go-sql-driver/mysql" + "github.com/mattn/go-sqlite3" "google.golang.org/genproto/protobuf/field_mask" "google.golang.org/protobuf/proto" "gorm.io/gorm" @@ -159,8 +161,12 @@ func TestDeleteShareByIDExactPrincipal(t *testing.T) { } func TestDeleteShareByKeyReceipt(t *testing.T) { - forEachDialect(t, func(t *testing.T, m *mgr) { - ctx, owner := ownerContext(t, "einstein") + forEachDialectConfig(t, func(t *testing.T, cfg map[string]any) { + m := openOCMManager(t, cfg) + writer := openOCMManager(t, cfg) + userCtx, owner := ownerContext(t, "einstein") + ctx, cancel := context.WithTimeout(userCtx, 10*time.Second) + defer cancel() now := time.Now().UTC().Truncate(time.Millisecond) m.db = m.db.Session(&gorm.Session{NowFunc: func() time.Time { return now }}) deleted := storeOutgoing(t, m, ctx, owner, "viewer", "tok-deleted") @@ -168,13 +174,24 @@ func TestDeleteShareByKeyReceipt(t *testing.T) { t.Fatal(err) } stored := storeOutgoing(t, m, ctx, owner, "viewer", "tok-k") - duplicate := storeOutgoing(t, m, ctx, owner, "editor", "tok-duplicate") + duplicate := storeOutgoing(t, m, ctx, owner, "viewer", "tok-duplicate") otherCtx, otherOwner := ownerContext(t, "another-owner") survivor := storeOutgoing(t, m, otherCtx, otherOwner, "viewer", "tok-survivor") ref := &ocm.ShareReference{Spec: &ocm.ShareReference_Key{Key: &ocm.ShareKey{ Owner: owner.Id, ResourceId: stored.ResourceId, Grantee: stored.Grantee, }}} + editor := share.NewWebDavAccessMethod(permissions.NewEditorRole().CS3ResourcePermissions(), nil, nil) + field := &ocm.UpdateOCMShareRequest_UpdateField{Field: &ocm.UpdateOCMShareRequest_UpdateField_AccessMethods{AccessMethods: editor}} + update, err := m.UpdateShare(ctx, owner, ref, field) + if err != nil || update == nil || update.After.GetId().GetOpaqueId() != stored.Id.OpaqueId || !update.WebDAVPermissionsChanged { + t.Fatalf("update did not change the lowest-ID live share: %v %v", update, err) + } + got, err := m.GetShare(ctx, owner, idRef(duplicate.Id)) + if err != nil || !proto.Equal(webdavPermissions(got.GetAccessMethods()), webdavPermissions(duplicate.GetAccessMethods())) { + t.Fatalf("update also changed the duplicate: %v", err) + } + const callback = "test:abort_second_ocm_delete" abort := errors.New("abort after deleting both rows") deletes := 0 @@ -200,7 +217,52 @@ func TestDeleteShareByKeyReceipt(t *testing.T) { t.Fatalf("rollback changed share %s: %v", want.GetId().GetOpaqueId(), err) } } - removals, err := m.DeleteShare(ctx, owner, ref) + deletePool, err := m.db.DB() + if err != nil { + t.Fatal(err) + } + gate := &transactionGate{DB: deletePool, mode: "commit", reached: make(chan struct{}), release: make(chan struct{})} + m.db.Statement.ConnPool = gate + writerPool, err := writer.db.DB() + if err != nil { + t.Fatal(err) + } + writerPool.SetMaxOpenConns(1) + sqlite := cfg["db_engine"] == "sqlite" + setTimeout := "SET SESSION innodb_lock_wait_timeout = 1" + if sqlite { + setTimeout = "PRAGMA busy_timeout = 0" + } + if _, err := writerPool.ExecContext(ctx, setTimeout); err != nil { + t.Fatal(err) + } + var removals []share.ShareRemoval + var deleteErr error + done := make(chan struct{}) + release := sync.OnceFunc(func() { close(gate.release) }) + go func() { + defer close(done) + removals, deleteErr = m.DeleteShare(ctx, owner, ref) + }() + defer func() { release(); <-done }() + select { + case <-gate.reached: + case <-done: + t.Fatalf("delete exited before commit: %v", deleteErr) + case <-ctx.Done(): + t.Fatal("delete did not reach commit") + } + up, lockErr := writer.UpdateShare(ctx, owner, ref, field) + var sqliteErr sqlite3.Error + var mysqlErr *mysql.MySQLError + if up != nil || (sqlite && (!errors.As(lockErr, &sqliteErr) || sqliteErr.Code != sqlite3.ErrBusy)) || + (!sqlite && (!errors.As(lockErr, &mysqlErr) || mysqlErr.Number != 1205)) { + t.Fatalf("competing update: %v, %v", up, lockErr) + } + t.Log("ordinary update encountered database contention during ordinary delete") + release() + <-done + err = deleteErr if err != nil || len(removals) != 2 { t.Fatalf("got %d receipts: %v", len(removals), err) } @@ -214,6 +276,9 @@ func TestDeleteShareByKeyReceipt(t *testing.T) { t.Errorf("share %s remains available: %v", want.Id.OpaqueId, err) } } + if updated, err := writer.UpdateShare(ctx, owner, ref, field); updated != nil || !errors.Is(err, share.ErrShareNotFound) { + t.Fatalf("update after delete: %v %v", updated, err) + } if removals, err := m.DeleteShare(ctx, owner, ref); !errors.Is(err, share.ErrShareNotFound) || removals != nil { t.Errorf("repeat returned %d receipts: %v", len(removals), err) } diff --git a/pkg/share/manager/sql/ocm_shares.go b/pkg/share/manager/sql/ocm_shares.go index d0290209c77..6e1fe2a5c58 100644 --- a/pkg/share/manager/sql/ocm_shares.go +++ b/pkg/share/manager/sql/ocm_shares.go @@ -19,6 +19,7 @@ package sql import ( + "cmp" "context" "encoding/json" "fmt" @@ -228,6 +229,9 @@ func forUpdate(tx *gorm.DB) *gorm.DB { return tx } +// Outgoing writers read rows in database tuple order to preserve collated equality. +const outgoingShareOrder = "instance, inode, share_with, id" + func lockOutgoingShares(tx *gorm.DB, user *userpb.User, ref *ocm.ShareReference) ([]model.OcmShare, error) { q := forUpdate(tx) key := ref.GetKey() @@ -247,7 +251,7 @@ func lockOutgoingShares(tx *gorm.DB, user *userpb.User, ref *ocm.ShareReference) return nil, errtypes.NotFound(ref.String()) } var matches []model.OcmShare - if err := q.Order("id").Find(&matches).Error; err != nil { + if err := q.Order(outgoingShareOrder).Find(&matches).Error; err != nil { return nil, err } // MySQL text collation can equate distinct opaque identifiers. @@ -276,6 +280,7 @@ func (m *mgr) DeleteShare(ctx context.Context, user *userpb.User, ref *ocm.Share if err != nil { return err } + // Exact key matches share the same tuple, so their receipt order is by ID. removals = make([]share.ShareRemoval, len(matches)) for i := range matches { row := &matches[i] @@ -301,24 +306,8 @@ func (m *mgr) DeleteShare(ctx context.Context, user *userpb.User, ref *ocm.Share return removals, nil } -// deleteLockedOCMShares soft-deletes only the rows its caller locked and authorized. +// deleteLockedOCMShares expects authorized rows already locked in outgoingShareOrder. func deleteLockedOCMShares(tx *gorm.DB, rows []model.OcmShare, changedErr error) error { - if len(rows) > 1 { - ids := make([]uint, 0, len(rows)) - for _, row := range rows { - ids = append(ids, row.Id) - } - // Database ordering keeps collated variants in the same tuple order. - var ordered []model.OcmShare - if err := forUpdate(tx).Select("id", "instance", "inode", "share_with"). - Where("id IN ?", ids).Order("instance, inode, share_with, id").Find(&ordered).Error; err != nil { - return err - } - if len(ordered) != len(rows) { - return changedErr - } - rows = ordered - } cutoff := tx.NowFunc().UTC().Truncate(time.Millisecond) for _, row := range rows { // The soft-delete timestamp participates in the unique key. Use its @@ -1102,7 +1091,7 @@ func (m *mgr) UpdateShare(ctx context.Context, user *userpb.User, ref *ocm.Share if err != nil { return err } - before := matches[0] + before := slices.MinFunc(matches, func(a, b model.OcmShare) int { return cmp.Compare(a.Id, b.Id) }) id := &ocm.ShareId{OpaqueId: strconv.FormatUint(uint64(before.Id), 10)} updates, accessMethodUpdates, err := m.queriesUpdatesOnShare(ctx, id, f...) if err != nil { From 1db0701e491e19d1f8592e9a45f13afe7b535ee3 Mon Sep 17 00:00:00 2001 From: Mahdi Baghbani Date: Thu, 26 Nov 2026 08:00:53 +0000 Subject: [PATCH 4/8] test(ocm): stabilize directed action concurrency Signed-off-by: Mahdi Baghbani --- pkg/ocm/share/contact.go | 10 +- .../manager/sql/ocm_directed_actions_test.go | 26 ++++- .../sql/ocm_directed_concurrency_test.go | 98 +++++++++++++------ 3 files changed, 98 insertions(+), 36 deletions(-) diff --git a/pkg/ocm/share/contact.go b/pkg/ocm/share/contact.go index ce2e9edd8cd..b12fa29ba47 100644 --- a/pkg/ocm/share/contact.go +++ b/pkg/ocm/share/contact.go @@ -24,12 +24,12 @@ import ( userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" ) -// DirectedShareActions is the transactional bulk surface of a repository: -// withdraw exact bound outgoing grants and reject exact bound received grants. +// DirectedShareActions withdraws or rejects exact bound grants for an +// authenticated local creator or recipient. // Historical grants without a complete binding remain available to ordinary -// per-share operations. Receipts cover only the eligible captured grants. -// Each direction commits the whole selection or returns an error without a -// receipt. A received selection with a transfer in progress is refused. +// per-share operations. Each direction changes its eligible selection atomically +// and returns receipts only after commit acknowledgment. CommitUnknownError +// leaves the outcome unknown. A received selection with a transfer in progress is refused. type DirectedShareActions interface { RemoveOCMSharesForRecipient(ctx context.Context, creator, recipient *userpb.UserId) ([]*ShareRemoval, error) RejectReceivedOCMSharesFromSender(ctx context.Context, recipient, sender *userpb.UserId) ([]*ReceivedShareUpdate, error) diff --git a/pkg/share/manager/sql/ocm_directed_actions_test.go b/pkg/share/manager/sql/ocm_directed_actions_test.go index 42f61024685..863701621c4 100644 --- a/pkg/share/manager/sql/ocm_directed_actions_test.go +++ b/pkg/share/manager/sql/ocm_directed_actions_test.go @@ -26,10 +26,12 @@ import ( userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" ocm "github.com/cs3org/go-cs3apis/cs3/sharing/ocm/v1beta1" provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" + "github.com/cs3org/reva/v3/pkg/errtypes" "github.com/cs3org/reva/v3/pkg/ocm/share" "github.com/cs3org/reva/v3/pkg/share/manager/sql/model" "github.com/mattn/go-sqlite3" "google.golang.org/genproto/protobuf/field_mask" + "google.golang.org/protobuf/proto" "gorm.io/gorm" ) @@ -167,6 +169,28 @@ func TestDirectedActionsRespectExactIdentities(t *testing.T) { if err != nil || initial.GetRemoteShareId() != "001.0" || initial.GetGrantee().GetUserId().GetOpaqueId() != "00012" { t.Fatalf("numeric-looking identities changed on read: %v %v", initial, err) } + blank := &userpb.User{Id: &userpb.UserId{OpaqueId: alice.OpaqueId, TenantId: alice.TenantId, Type: alice.Type}} + blankGrant := grantShare(blank, bob.Idp, "incoming-blank-idp", file) + blankGrant.Creator = bob + stored, err := m.StoreReceivedShareForResolvedRecipient(ctx, blankGrant, blank.Id) + if err != nil { + t.Fatal(err) + } + if receivedRow(t, m, stored.Id.OpaqueId).GrantKey == nil { + t.Fatal("resolved blank-IdP grant has no key") + } + before, err := m.GetReceivedShare(ctx, blank, idRef(stored.Id)) + if err != nil || before.GetState() != ocm.ShareState_SHARE_STATE_PENDING || before.GetHidden() { + t.Fatalf("ordinary read of resolved blank-IdP grant: %v, %v", before, err) + } + var badRequest errtypes.BadRequest + if receipts, err := m.RejectReceivedOCMSharesFromSender(ctx, blank.Id, bob); !errors.As(err, &badRequest) || receipts != nil { + t.Fatalf("directed decline for blank IdP returned receipts %v, error %v", receipts, err) + } + after, err := m.GetReceivedShare(ctx, blank, idRef(stored.Id)) + if err != nil || !proto.Equal(before, after) { + t.Fatalf("refused decline changed resolved blank-IdP grant: %v, %v", after, err) + } other := incoming(otherDirectory, bob, "incoming-two") tenantNeighbor := incoming(otherTenant, bob, "incoming-other-tenant") caseSender := &userpb.UserId{OpaqueId: "BOB", Idp: bob.Idp, Type: bob.Type} @@ -660,7 +684,7 @@ func TestDirectedWithdrawalRejectsInvalidSelectionAtomically(t *testing.T) { if err := m.db.Model(&model.OcmShare{}).Where("id = ?", ids[1].OpaqueId).Update("item_type", "invalid").Error; err != nil { t.Fatal(err) } - if receipts, err := m.RemoveOCMSharesForRecipient(ctx, alice, bob); err == nil || receipts != nil { + if receipts, err := m.RemoveOCMSharesForRecipient(ctx, alice, bob); !errors.Is(err, share.ErrInvalidResourceType) || receipts != nil { t.Fatalf("invalid selection returned receipts %v, error %v", receipts, err) } var remaining int64 diff --git a/pkg/share/manager/sql/ocm_directed_concurrency_test.go b/pkg/share/manager/sql/ocm_directed_concurrency_test.go index 9f1cc3d523d..e118c5ebe4a 100644 --- a/pkg/share/manager/sql/ocm_directed_concurrency_test.go +++ b/pkg/share/manager/sql/ocm_directed_concurrency_test.go @@ -33,10 +33,11 @@ import ( // It is confined to the action's pool; the other manager uses a separate pool. type transactionGate struct { *dbsql.DB - mode string - reached chan struct{} - release chan struct{} - fired atomic.Bool + mode string + reached chan struct{} + release chan struct{} + rollbackFailed chan error + fired atomic.Bool } type gatedTx struct { *dbsql.Tx @@ -60,6 +61,10 @@ func (t *gatedTx) Commit() error { func (t *gatedTx) Rollback() error { err := t.Tx.Rollback() if t.gate.mode == "retry" && t.gate.fired.CompareAndSwap(false, true) { + if err != nil { + t.gate.rollbackFailed <- err + return err + } close(t.gate.reached) <-t.gate.release } @@ -105,35 +110,27 @@ func TestDirectedTransactionConcurrentSelectionAndRetry(t *testing.T) { if err != nil { t.Fatal(err) } + sqlite := cfg["db_engine"] == "sqlite" + if mode == "commit" && !sqlite { + // InnoDB gap locks protect the captured selection at this isolation. + m.db = observer(t, cfg, "REPEATABLE-READ") + t.Log("MySQL action pool session isolation: REPEATABLE-READ") + } db, err := m.db.DB() if err != nil { t.Fatal(err) } - gate := &transactionGate{DB: db, mode: mode, reached: make(chan struct{}), release: make(chan struct{})} + gate := &transactionGate{ + DB: db, mode: mode, reached: make(chan struct{}), release: make(chan struct{}), rollbackFailed: make(chan error, 1), + } release := sync.OnceFunc(func() { close(gate.release) }) - defer release() m.db.Statement.ConnPool = gate var laterID *ocm.ShareId - sqlite := cfg["db_engine"] == "sqlite" - if mode == "commit" { - if direction == "outgoing" { - laterID, err = writer.GenerateID(ctx) - if err != nil { - t.Fatal(err) - } - } - pool, err := writer.db.DB() + if mode == "commit" && direction == "outgoing" { + laterID, err = writer.GenerateID(ctx) if err != nil { t.Fatal(err) } - pool.SetMaxOpenConns(1) - setTimeout := "SET SESSION innodb_lock_wait_timeout = 1" - if sqlite { - setTimeout = "PRAGMA busy_timeout = 0" - } - if _, err := pool.ExecContext(ctx, setTimeout); err != nil { - t.Fatal(err) - } } var injected atomic.Bool if mode == "retry" { @@ -157,6 +154,7 @@ func TestDirectedTransactionConcurrentSelectionAndRetry(t *testing.T) { } done := make(chan result, 1) go func() { + defer close(done) var out result if direction == "outgoing" { receipts, err := m.RemoveOCMSharesForRecipient(ctx, alice, bob) @@ -173,8 +171,23 @@ func TestDirectedTransactionConcurrentSelectionAndRetry(t *testing.T) { } done <- out }() + defer func() { + release() + cancel() + for range done { + } + }() select { case <-gate.reached: + case action := <-done: + select { + case err := <-gate.rollbackFailed: + t.Fatalf("rollback before retry barrier: %v", err) + default: + t.Fatalf("action returned before %s barrier: error %v, receipt IDs %v", mode, action.err, action.ids) + } + case err := <-gate.rollbackFailed: + t.Fatalf("rollback before retry barrier: %v", err) case <-ctx.Done(): t.Fatal("transaction did not reach barrier") } @@ -182,7 +195,29 @@ func TestDirectedTransactionConcurrentSelectionAndRetry(t *testing.T) { if mode == "commit" { // The action cannot commit until a real competing write // has been refused by the database. - _, lockErr := store(writer, token, laterID) + var lockErr error + if err := writer.db.WithContext(ctx).Connection(func(db *gorm.DB) error { + setTimeout := "SET SESSION innodb_lock_wait_timeout = 1" + readTimeout, want := "SELECT @@SESSION.innodb_lock_wait_timeout", 1 + if sqlite { + setTimeout = "PRAGMA busy_timeout = 0" + readTimeout, want = "PRAGMA busy_timeout", 0 + } + if err := db.Exec(setTimeout).Error; err != nil { + return err + } + var got int + if err := db.Raw(readTimeout).Row().Scan(&got); err != nil { + return err + } + if got != want { + t.Fatalf("writer session lock wait timeout %d, want %d", got, want) + } + _, lockErr = store(&mgr{c: writer.c, db: db}, token, laterID) + return nil + }); err != nil { + t.Fatalf("configure competing writer session: %v", err) + } var sqliteErr sqlite3.Error var mysqlErr *mysql.MySQLError if sqlite { @@ -192,7 +227,7 @@ func TestDirectedTransactionConcurrentSelectionAndRetry(t *testing.T) { } else if !errors.As(lockErr, &mysqlErr) || mysqlErr.Number != 1205 { t.Fatalf("competing store during InnoDB transaction: %v, want lock wait timeout", lockErr) } - t.Logf("competing %s store reported lock contention before commit", direction) + t.Logf("competing %s store before commit: %v", direction, lockErr) release() } var later string @@ -209,9 +244,6 @@ func TestDirectedTransactionConcurrentSelectionAndRetry(t *testing.T) { case <-ctx.Done(): t.Fatal("action did not complete") } - if mode == "commit" { - later, writerErr = store(writer, token, laterID) - } if action.err != nil || writerErr != nil { t.Fatalf("action: %v, writer: %v", action.err, writerErr) } @@ -222,6 +254,12 @@ func TestDirectedTransactionConcurrentSelectionAndRetry(t *testing.T) { if !slices.Equal(action.ids, want) { t.Fatalf("receipts %v, want %v", action.ids, want) } + if mode == "commit" { + later, writerErr = store(writer, token, laterID) + if writerErr != nil { + t.Fatalf("competing store after acknowledged commit: %v", writerErr) + } + } if direction == "outgoing" { var current []model.OcmShare if err := writer.db.Where("id IN ?", []string{original, later}).Find(¤t).Error; err != nil { @@ -243,8 +281,8 @@ func TestDirectedTransactionConcurrentSelectionAndRetry(t *testing.T) { if mode == "retry" { expected = ocm.ShareState_SHARE_STATE_REJECTED } - if got.State != expected { - t.Fatalf("later state %v, expected %v", got.State, expected) + if got.State != expected || got.Hidden != (mode == "retry") { + t.Fatalf("later grant state %v, hidden %t, want state %v, hidden %t", got.State, got.Hidden, expected, mode == "retry") } } }) From efbc4da2ecd5b94c3e046705ef0de3701e8049d4 Mon Sep 17 00:00:00 2001 From: Mahdi Baghbani Date: Thu, 26 Nov 2026 12:56:06 +0000 Subject: [PATCH 5/8] fix(ocm): keep embedded transfer reservations Signed-off-by: Mahdi Baghbani --- .../ocmshareprovider/embedded_route_test.go | 30 +- .../ocmshareprovider_emit_test.go | 287 ++++++++++++++++-- .../manager/sql/ocm_directed_actions_test.go | 27 +- pkg/share/manager/sql/ocm_receipts_test.go | 71 ++++- pkg/share/manager/sql/ocm_shares.go | 12 +- 5 files changed, 382 insertions(+), 45 deletions(-) diff --git a/internal/grpc/services/ocmshareprovider/embedded_route_test.go b/internal/grpc/services/ocmshareprovider/embedded_route_test.go index 4f7410f1044..df8c3b088b0 100644 --- a/internal/grpc/services/ocmshareprovider/embedded_route_test.go +++ b/internal/grpc/services/ocmshareprovider/embedded_route_test.go @@ -122,10 +122,8 @@ func (r unacknowledgedTransferStart) StartReceivedShareTransfer(ctx context.Cont return receipt, errCommitAcknowledgmentLost } -func TestMountedEmbeddedShareProcessing(t *testing.T) { - e := newEmitEnv(t) - jwtConfig := map[string]any{"secret": "embedded-route-test"} - tokenManagers := map[string]map[string]any{"jwt": jwtConfig} +func mountEmbeddedGateway(t *testing.T, e *emitEnv, tokenManagers map[string]map[string]any) (mountedGateway, *mountedEmbeddedPeers) { + t.Helper() gw, err := revagateway.New(e.recip, map[string]any{ "data_transfers_folder": "/transfers", "token_managers": tokenManagers, @@ -137,7 +135,26 @@ func TestMountedEmbeddedShareProcessing(t *testing.T) { peers := &mountedEmbeddedPeers{provider: e.svc} testGateways.embedded = peers t.Cleanup(func() { testGateways.embedded = nil }) - stampGateway(mountedGateway{server: gw.(gateway.GatewayAPIServer)}) + client := mountedGateway{server: gw.(gateway.GatewayAPIServer)} + stampGateway(client) + return client, peers +} + +func TestMountedEmbeddedShareProcessing(t *testing.T) { + e := newEmitEnv(t) + jwtConfig := map[string]any{"secret": "embedded-route-test"} + tokenManagers := map[string]map[string]any{"jwt": jwtConfig} + gw, peers := mountEmbeddedGateway(t, e, tokenManagers) + update := func(id *ocm.ShareId, state ocm.ShareState, destination string, want rpc.Code) { + t.Helper() + res, err := gw.UpdateReceivedOCMShare(e.recip, &ocm.UpdateReceivedOCMShareRequest{ + Share: &ocm.ReceivedShare{Id: id, State: state, Destination: destination}, + UpdateMask: &field_mask.FieldMask{Paths: []string{"state"}}, + }) + if err != nil || res.GetStatus() == nil || res.GetStatus().GetCode() != want { + t.Fatalf("update to %v: status %v, error %v, want %v", state, res.GetStatus(), err, want) + } + } mesh, err := sciencemesh.New(e.recip, map[string]any{ "gatewaysvc": "gateway", "mesh_directory_url": "https://directory.example.org", @@ -252,6 +269,9 @@ func TestMountedEmbeddedShareProcessing(t *testing.T) { t.Fatalf("HTTP %d, want 500", code) } requireState(t, rs.Id, ocm.ShareState_SHARE_STATE_TRANSFERRING) + update(rs.Id, ocm.ShareState_SHARE_STATE_PENDING, "", rpc.Code_CODE_ABORTED) + update(rs.Id, ocm.ShareState_SHARE_STATE_ACCEPTED, "/dest", rpc.Code_CODE_FAILED_PRECONDITION) + requireState(t, rs.Id, ocm.ShareState_SHARE_STATE_TRANSFERRING) if len(e.xfer.callbacks) != 0 || peers.datatxCalls != 0 { t.Fatal("transfer started without an acknowledged commit") } diff --git a/internal/grpc/services/ocmshareprovider/ocmshareprovider_emit_test.go b/internal/grpc/services/ocmshareprovider/ocmshareprovider_emit_test.go index cbad3b9bdf4..c39cc05a957 100644 --- a/internal/grpc/services/ocmshareprovider/ocmshareprovider_emit_test.go +++ b/internal/grpc/services/ocmshareprovider/ocmshareprovider_emit_test.go @@ -22,13 +22,16 @@ import ( "bytes" "context" "crypto/x509" + "database/sql" "encoding/json" "errors" "io" "net" "net/http" "net/http/httptest" + "os" "path/filepath" + "reflect" "slices" "strconv" "strings" @@ -55,10 +58,13 @@ import ( "github.com/cs3org/reva/v3/pkg/permissions" sqlmgr "github.com/cs3org/reva/v3/pkg/share/manager/sql" model "github.com/cs3org/reva/v3/pkg/share/manager/sql/model" + mysql "github.com/go-sql-driver/mysql" + "github.com/google/uuid" "github.com/rs/zerolog" "google.golang.org/genproto/protobuf/field_mask" "google.golang.org/grpc" "google.golang.org/protobuf/proto" + gormmysql "gorm.io/driver/mysql" "gorm.io/driver/sqlite" "gorm.io/gorm" ) @@ -172,6 +178,7 @@ type controlledTransferrer struct { mu sync.Mutex callbacks []func(error) fail error + park func(func(error)) } func (c *controlledTransferrer) Process(_ context.Context, _ string, _ string, done func(error)) error { @@ -181,6 +188,10 @@ func (c *controlledTransferrer) Process(_ context.Context, _ string, _ string, d return c.fail } c.callbacks = append(c.callbacks, done) + if c.park != nil { + go c.park(done) + c.park = nil + } return nil } @@ -223,10 +234,17 @@ type emitEnv struct { func newEmitEnv(t *testing.T) *emitEnv { t.Helper() dbPath := filepath.Join(t.TempDir(), "ocm.sqlite") - repo, err := sqlmgr.NewOCMShareManager(context.Background(), map[string]any{ + e := newEmitEnvWithDatabase(t, map[string]any{ "db_engine": "sqlite", "db_name": dbPath, }) + e.dbPath = dbPath + return e +} + +func newEmitEnvWithDatabase(t *testing.T, dbConfig map[string]any) *emitEnv { + t.Helper() + repo, err := sqlmgr.NewOCMShareManager(context.Background(), dbConfig) if err != nil { t.Fatal(err) } @@ -251,11 +269,10 @@ func newEmitEnv(t *testing.T) *emitEnv { key: key, }, }, - repo: repo, - peer: peer, - xfer: xfer, - logs: &lockedBuffer{}, - dbPath: dbPath, + repo: repo, + peer: peer, + xfer: xfer, + logs: &lockedBuffer{}, } logger := zerolog.New(env.logs) env.owner = appctx.WithLogger(appctx.ContextSetUser(context.Background(), &userpb.User{ @@ -460,6 +477,22 @@ type failingRepo struct { var errCommitAcknowledgmentLost = errors.New("commit acknowledgment lost") +type unacknowledgedTransferCompletion struct { + share.Repository + applied bool +} + +func (r unacknowledgedTransferCompletion) CompleteReceivedShareTransfer(ctx context.Context, user *userpb.User, id *ocm.ShareId, generation uint64, state ocm.ShareState) (*share.ReceivedShareUpdate, error) { + if r.applied { + receipt, err := r.Repository.CompleteReceivedShareTransfer(ctx, user, id, generation, state) + if err != nil { + return nil, err + } + return receipt, &share.CommitUnknownError{Observed: share.CommitObservedRequested} + } + return nil, &share.CommitUnknownError{Observed: share.CommitObservedPrevious} +} + func (r failingRepo) DeleteShare(ctx context.Context, user *userpb.User, ref *ocm.ShareReference) ([]share.ShareRemoval, error) { if r.loseCommitAcknowledgment { receipt, err := r.Repository.DeleteShare(ctx, user, ref) @@ -642,7 +675,9 @@ func TestReceivedStateTransitionsEmitOnce(t *testing.T) { e.setState(t, rs.Id, ocm.ShareState_SHARE_STATE_REJECTED, "") requireNotices(t, e.peer, ocmd.NotificationShareAccepted, ocmd.NotificationShareDeclined) e.setState(t, rs.Id, ocm.ShareState_SHARE_STATE_PENDING, "") - e.setState(t, rs.Id, ocm.ShareState_SHARE_STATE_TRANSFERRING, "") + if res := e.setState(t, rs.Id, ocm.ShareState_SHARE_STATE_TRANSFERRING, ""); res.GetStatus().GetCode() != rpc.Code_CODE_INVALID_ARGUMENT { + t.Fatalf("ordinary entry: %v", res.GetStatus()) + } requireNotices(t, e.peer, ocmd.NotificationShareAccepted, ocmd.NotificationShareDeclined) } @@ -779,35 +814,247 @@ func TestEmbeddedAcceptanceNeedsCompletedCopy(t *testing.T) { } func TestDirectedDeclineRefusesServiceCopyUntilCompletion(t *testing.T) { - e := newEmitEnv(t) - recipient := appctx.ContextMustGetUser(e.recip).Id - recipient.Type = userpb.UserType_USER_TYPE_PRIMARY + t.Run("sqlite", func(t *testing.T) { + e := newEmitEnv(t) + checkDirectedDeclineDuringCopy(t, e, sqlite.Open(e.dbPath)) + }) + t.Run("mysql", func(t *testing.T) { + raw := os.Getenv("REVA_TEST_MYSQL") + if raw == "" { + t.Skip("disposable MySQL fixture is unavailable") + } + at := strings.LastIndexByte(raw, '@') + if at < 0 { + t.Fatal("invalid REVA_TEST_MYSQL address") + } + host, portText, err := net.SplitHostPort(raw[at+1:]) + if err != nil { + t.Fatal("invalid REVA_TEST_MYSQL host and port") + } + port, err := strconv.Atoi(portText) + user, password, ok := strings.Cut(raw[:at], ":") + if err != nil || !ok { + t.Fatal("invalid REVA_TEST_MYSQL credentials or port") + } + target := mysql.NewConfig() + target.User, target.Passwd, target.Net, target.Addr = user, password, "tcp", raw[at+1:] + admin, err := sql.Open("mysql", target.FormatDSN()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = admin.Close() }) + name := "ocm_copy_" + strings.ReplaceAll(uuid.NewString(), "-", "") + if _, err := admin.Exec("CREATE DATABASE " + name + " CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci"); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if _, err := admin.Exec("DROP DATABASE " + name); err != nil { + t.Errorf("drop disposable schema: %v", err) + } + }) + e := newEmitEnvWithDatabase(t, map[string]any{ + "db_engine": "mysql", "db_username": user, "db_password": password, + "db_host": host, "db_port": port, "db_name": name, + }) + target.DBName, target.ParseTime = name, true + checkDirectedDeclineDuringCopy(t, e, gormmysql.Open(target.FormatDSN())) + }) +} + +func checkDirectedDeclineDuringCopy(t *testing.T, e *emitEnv, dialect gorm.Dialector) { + t.Helper() + gw, peers := mountEmbeddedGateway(t, e, map[string]map[string]any{"jwt": {"secret": "embedded-route-test"}}) + db, err := gorm.Open(dialect, &gorm.Config{}) + if err != nil { + t.Fatal(err) + } + pool, err := db.DB() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = pool.Close() }) + type projection struct { + row model.OcmReceivedShare + protocols []model.OcmReceivedShareProtocol + } + snapshot := func(t *testing.T, id *ocm.ShareId) projection { + t.Helper() + var p projection + if err := db.Where("id = ?", id.OpaqueId).Take(&p.row).Error; err != nil { + t.Fatal(err) + } + if err := db.Where("ocm_received_share_id = ?", p.row.ID).Order("id").Find(&p.protocols).Error; err != nil { + t.Fatal(err) + } + return p + } + + recipient := appctx.ContextMustGetUser(e.recip) + recipient.Id.Type = userpb.UserType_USER_TYPE_PRIMARY + other := e.received(t, "directed-first", false) rs := e.received(t, "directed-copy", true) sender := &userpb.UserId{OpaqueId: "alice", Idp: e.peer.host()} actions := e.repo.(share.DirectedShareActions) + update := func(t *testing.T, id *ocm.ShareId, state ocm.ShareState, hidden bool, want rpc.Code, paths ...string) { + t.Helper() + res, err := gw.UpdateReceivedOCMShare(e.recip, &ocm.UpdateReceivedOCMShareRequest{ + Share: &ocm.ReceivedShare{Id: id, State: state, Destination: "/home/dest", Hidden: hidden}, + UpdateMask: &field_mask.FieldMask{Paths: paths}, + }) + if err != nil || res.GetStatus() == nil || res.GetStatus().GetCode() != want { + t.Fatalf("update %v to %v: status %v, error %v, want %v", paths, state, res.GetStatus(), err, want) + } + } - if res := e.setState(t, rs.Id, ocm.ShareState_SHARE_STATE_ACCEPTED, "/home/dest"); res.Status.Code != rpc.Code_CODE_OK { - t.Fatalf("start: %v", res.Status) + beforeOther := snapshot(t, other.Id) + beforeCopy := snapshot(t, rs.Id) + update(t, rs.Id, ocm.ShareState_SHARE_STATE_TRANSFERRING, true, rpc.Code_CODE_INVALID_ARGUMENT, "state", "hidden") + if !reflect.DeepEqual(beforeCopy, snapshot(t, rs.Id)) { + t.Fatal("refused entry changed the stored projection") } - updates, err := actions.RejectReceivedOCMSharesFromSender(e.recip, recipient, sender) + + started, finished := make(chan struct{}), make(chan struct{}) + release := make(chan struct{}) + finish := sync.OnceFunc(func() { close(release) }) + e.xfer.park = func(done func(error)) { + close(started) + <-release + done(nil) + close(finished) + } + wait := func(ch <-chan struct{}) { + t.Helper() + select { + case <-ch: + case <-time.After(5 * time.Second): + t.Fatal("timed out waiting for the controlled copy") + } + } + t.Cleanup(func() { + finish() + if len(e.xfer.callbacks) > 0 { + wait(finished) + } + }) + update(t, rs.Id, ocm.ShareState_SHARE_STATE_ACCEPTED, false, rpc.Code_CODE_OK, "state") + wait(started) + beforeCopy = snapshot(t, rs.Id) + gen := beforeCopy.row.TransferGeneration + if beforeCopy.row.State != model.OcmShareStateTransferring || gen == 0 { + t.Fatal("copy started without a reservation") + } + update(t, rs.Id, ocm.ShareState_SHARE_STATE_PENDING, false, rpc.Code_CODE_ABORTED, "state") + update(t, rs.Id, ocm.ShareState_SHARE_STATE_REJECTED, false, rpc.Code_CODE_ABORTED, "state") + update(t, rs.Id, ocm.ShareState_SHARE_STATE_REJECTED, true, rpc.Code_CODE_ABORTED, "state", "hidden") + if u, err := e.repo.CompleteReceivedShareTransfer(e.recip, recipient, rs.Id, gen+1, ocm.ShareState_SHARE_STATE_ACCEPTED); err != nil || + u == nil || u.After.GetState() != ocm.ShareState_SHARE_STATE_TRANSFERRING || !proto.Equal(u.Before, u.After) { + t.Fatalf("wrong-generation completion receipt %v, error %v", u, err) + } + if !reflect.DeepEqual(beforeCopy, snapshot(t, rs.Id)) || !reflect.DeepEqual(beforeOther, snapshot(t, other.Id)) { + t.Fatal("refused state changes altered a stored projection") + } + + updates, err := actions.RejectReceivedOCMSharesFromSender(e.recip, recipient.Id, sender) if updates != nil || !errors.Is(err, share.ErrTransferInProgress) { t.Fatalf("directed decline returned %d receipts and %v", len(updates), err) } - if res := e.setState(t, rs.Id, ocm.ShareState_SHARE_STATE_ACCEPTED, "/home/dest"); res.Status.Code != rpc.Code_CODE_FAILED_PRECONDITION { - t.Fatalf("second start: %v", res.Status) + if !reflect.DeepEqual(beforeCopy, snapshot(t, rs.Id)) || !reflect.DeepEqual(beforeOther, snapshot(t, other.Id)) { + t.Fatal("refused batch changed a stored projection") } - if len(e.xfer.callbacks) != 1 { - t.Fatalf("started %d copies", len(e.xfer.callbacks)) + update(t, rs.Id, ocm.ShareState_SHARE_STATE_ACCEPTED, false, rpc.Code_CODE_FAILED_PRECONDITION, "state") + update(t, rs.Id, ocm.ShareState_SHARE_STATE_PENDING, true, rpc.Code_CODE_OK, "hidden") + got := snapshot(t, rs.Id) + if !got.row.Hidden || got.row.State != model.OcmShareStateTransferring || got.row.TransferGeneration != gen || + !reflect.DeepEqual(beforeCopy.protocols, got.protocols) { + t.Fatal("hidden-only update did not preserve the reservation and protocols") + } + update(t, other.Id, ocm.ShareState_SHARE_STATE_PENDING, true, rpc.Code_CODE_OK, "hidden") + if got := snapshot(t, other.Id).row; !got.Hidden || got.State != model.OcmShareStatePending { + t.Fatal("unrelated masked update did not apply") + } + if len(e.xfer.callbacks) != 1 || peers.datatxCalls != 0 || len(e.svc.notifier.(*syncNotifier).results) != 0 { + t.Fatal("a refused operation started another copy or attempted a peer notice") } requireNotices(t, e.peer) + finish() + wait(finished) + notices := requireNotices(t, e.peer, ocmd.NotificationShareAccepted) + if fileOf(notices[0])["providerId"] != rs.RemoteShareId { + t.Fatal("completion announced the wrong grant") + } e.xfer.callback(0)(nil) requireNotices(t, e.peer, ocmd.NotificationShareAccepted) + if got := snapshot(t, rs.Id).row; got.State != model.OcmShareStateAccepted || got.TransferGeneration != gen || !got.Hidden { + t.Fatal("owner completion did not preserve the generation and hidden flag") + } - updates, err = actions.RejectReceivedOCMSharesFromSender(e.recip, recipient, sender) - if err != nil || len(updates) != 1 || updates[0].Before.GetState() != ocm.ShareState_SHARE_STATE_ACCEPTED || - updates[0].After.GetState() != ocm.ShareState_SHARE_STATE_REJECTED { + updates, err = actions.RejectReceivedOCMSharesFromSender(e.recip, recipient.Id, sender) + if err != nil || len(updates) != 2 { t.Fatalf("directed decline after completion returned %d receipts and %v", len(updates), err) } + for i, want := range []*ocm.ReceivedShare{other, rs} { + u := updates[i] + before := []ocm.ShareState{ocm.ShareState_SHARE_STATE_PENDING, ocm.ShareState_SHARE_STATE_ACCEPTED}[i] + if !proto.Equal(u.Before.GetId(), want.Id) || !proto.Equal(u.After.GetId(), want.Id) || + u.Before.GetState() != before || u.After.GetState() != ocm.ShareState_SHARE_STATE_REJECTED || !u.After.GetHidden() { + t.Fatalf("unexpected decline receipt %d for %s", i, want.Id.OpaqueId) + } + } + update(t, other.Id, ocm.ShareState_SHARE_STATE_ACCEPTED, false, rpc.Code_CODE_OK, "state") + update(t, other.Id, ocm.ShareState_SHARE_STATE_PENDING, false, rpc.Code_CODE_OK, "state") + if got := snapshot(t, other.Id).row.State; got != model.OcmShareStatePending { + t.Fatal("ordinary access reset did not persist") + } + requireNotices(t, e.peer, ocmd.NotificationShareAccepted, ocmd.NotificationShareAccepted) + + for _, tc := range []struct { + name string + applied bool + state model.OcmShareState + }{ + {"unapplied terminal commit", false, model.OcmShareStateTransferring}, + {"applied terminal commit", true, model.OcmShareStateAccepted}, + } { + t.Run(tc.name, func(t *testing.T) { + rs := e.received(t, tc.name, true) + starts := len(e.xfer.callbacks) + update(t, rs.Id, ocm.ShareState_SHARE_STATE_ACCEPTED, false, rpc.Code_CODE_OK, "state") + reservation := snapshot(t, rs.Id) + e.svc.repo = unacknowledgedTransferCompletion{Repository: e.repo, applied: tc.applied} + t.Cleanup(func() { e.svc.repo = e.repo }) + e.xfer.callback(starts)(nil) + stored := snapshot(t, rs.Id) + if stored.row.State != tc.state || stored.row.TransferGeneration != reservation.row.TransferGeneration || + !reflect.DeepEqual(stored.protocols, reservation.protocols) { + t.Fatalf("unknown completion changed the reservation unexpectedly: %v", stored.row.State) + } + if !tc.applied { + update(t, rs.Id, ocm.ShareState_SHARE_STATE_PENDING, true, rpc.Code_CODE_ABORTED, "state", "hidden") + if !reflect.DeepEqual(reservation, snapshot(t, rs.Id)) { + t.Fatal("unresolved reservation changed") + } + } + update(t, rs.Id, ocm.ShareState_SHARE_STATE_ACCEPTED, false, rpc.Code_CODE_FAILED_PRECONDITION, "state") + if len(e.xfer.callbacks) != starts+1 || peers.datatxCalls != 0 || len(e.svc.notifier.(*syncNotifier).results) != 2 { + t.Fatal("unknown completion triggered a second dispatch or notice") + } + requireNotices(t, e.peer, ocmd.NotificationShareAccepted, ocmd.NotificationShareAccepted) + }) + } + + failed := e.received(t, "no dispatch", true) + starts := len(e.xfer.callbacks) + e.xfer.fail = errors.New("cannot dispatch copy") + update(t, failed.Id, ocm.ShareState_SHARE_STATE_ACCEPTED, false, rpc.Code_CODE_INTERNAL, "state") + rejected := snapshot(t, failed.Id) + if rejected.row.State != model.OcmShareStateRejected || rejected.row.TransferGeneration == 0 || len(e.xfer.callbacks) != starts { + t.Fatal("synchronous no-dispatch failure did not complete its reservation") + } + u, err := e.repo.CompleteReceivedShareTransfer(e.recip, recipient, failed.Id, rejected.row.TransferGeneration, ocm.ShareState_SHARE_STATE_ACCEPTED) + if err != nil || u == nil || u.StateChanged() || !reflect.DeepEqual(rejected, snapshot(t, failed.Id)) { + t.Fatalf("completed generation changed the failed projection: %v", err) + } + requireNotices(t, e.peer, ocmd.NotificationShareAccepted, ocmd.NotificationShareAccepted) } func TestSenderFailureKeepsCommittedChange(t *testing.T) { diff --git a/pkg/share/manager/sql/ocm_directed_actions_test.go b/pkg/share/manager/sql/ocm_directed_actions_test.go index 863701621c4..d014e2bcffb 100644 --- a/pkg/share/manager/sql/ocm_directed_actions_test.go +++ b/pkg/share/manager/sql/ocm_directed_actions_test.go @@ -272,16 +272,31 @@ func TestDirectedDeclineRefusesLiveTransfer(t *testing.T) { t.Fatal(err) } + projection := func(id *ocm.ShareId) *receivedProjection { + t.Helper() + row := receivedRow(t, m, id.OpaqueId) + got, err := readReceivedProjection(m.db, row.ID) + if err != nil { + t.Fatal(err) + } + return got + } + beforePending, beforeCopy := projection(pending.Id), projection(copying.Id) + reset := &ocm.ReceivedShare{Id: copying.Id, State: ocm.ShareState_SHARE_STATE_PENDING, Hidden: true} + if update, err := m.UpdateReceivedShare(ctx, alice, reset, &field_mask.FieldMask{Paths: []string{"state", "hidden"}}); update != nil || + !errors.Is(err, share.ErrTransferInProgress) { + t.Fatalf("ordinary reset receipt %v, error %v", update, err) + } + if !beforeCopy.equal(projection(copying.Id)) { + t.Fatal("refused reset changed the copy projection") + } + updates, err := m.RejectReceivedOCMSharesFromSender(ctx, alice.Id, bob) if updates != nil || !errors.Is(err, share.ErrTransferInProgress) { t.Fatalf("directed decline returned %d receipts and %v", len(updates), err) } - if got := receivedRow(t, m, pending.Id.OpaqueId); got.State != model.OcmShareStatePending || got.Hidden { - t.Fatalf("pending grant changed: state %v, hidden %t", got.State, got.Hidden) - } - if got := receivedRow(t, m, copying.Id.OpaqueId); got.State != model.OcmShareStateTransferring || - got.Hidden || got.TransferGeneration != transfer.Generation { - t.Fatalf("copy reservation changed: state %v, hidden %t, generation %d", got.State, got.Hidden, got.TransferGeneration) + if !beforePending.equal(projection(pending.Id)) || !beforeCopy.equal(projection(copying.Id)) { + t.Fatal("refused decline changed a selected projection") } if _, err := m.StartReceivedShareTransfer(ctx, alice, copying, stateMask()); !errors.Is(err, share.ErrTransferInProgress) { t.Fatalf("second transfer start: %v", err) diff --git a/pkg/share/manager/sql/ocm_receipts_test.go b/pkg/share/manager/sql/ocm_receipts_test.go index 44fe5b8b449..ad00e0858c4 100644 --- a/pkg/share/manager/sql/ocm_receipts_test.go +++ b/pkg/share/manager/sql/ocm_receipts_test.go @@ -600,28 +600,75 @@ func TestTransferAttemptLifecycle(t *testing.T) { if err != nil || second.Generation <= start.Generation { t.Fatalf("second attempt: %v %v", second, err) } - if u, err := m.CompleteReceivedShareTransfer(ctx, user, rs.Id, start.Generation, ocm.ShareState_SHARE_STATE_REJECTED); err != nil || u == nil || !proto.Equal(u.Before, second.Share) || !proto.Equal(u.After, second.Share) { + if u, err := m.CompleteReceivedShareTransfer(ctx, user, rs.Id, start.Generation, ocm.ShareState_SHARE_STATE_REJECTED); err != nil || u == nil || + !proto.Equal(u.Before, second.Share) || !proto.Equal(u.After, second.Share) { t.Fatalf("stale callback completed a newer attempt: %v %v", u, err) } - if got := receivedGeneration(t, m, rs.Id); got != second.Generation { - t.Fatalf("stale callback changed generation to %d, want %d", got, second.Generation) + + u, err = m.CompleteReceivedShareTransfer(ctx, user, rs.Id, second.Generation, ocm.ShareState_SHARE_STATE_ACCEPTED) + if err != nil || u == nil || !proto.Equal(u.Before, second.Share) || u.After.GetState() != ocm.ShareState_SHARE_STATE_ACCEPTED { + t.Fatalf("complete second attempt: %v %v", u, err) + } + resetReceipt, err := m.UpdateReceivedShare(ctx, user, reset, stateMask()) + if err != nil { + t.Fatal(err) + } + pending, err := m.GetReceivedShare(ctx, user, idRef(rs.Id)) + if err != nil || pending.GetState() != ocm.ShareState_SHARE_STATE_PENDING || !proto.Equal(pending, resetReceipt.After) { + t.Fatalf("reset readback: %v %v", pending, err) } + gen := receivedGeneration(t, m, rs.Id) + if u, err := m.CompleteReceivedShareTransfer(ctx, user, rs.Id, second.Generation, ocm.ShareState_SHARE_STATE_ACCEPTED); err != nil || u == nil || + !proto.Equal(u.Before, pending) || !proto.Equal(u.After, pending) { + t.Fatalf("stale callback changed the reset share: %v %v", u, err) + } + if got, err := m.GetReceivedShare(ctx, user, idRef(rs.Id)); err != nil || !proto.Equal(got, pending) || receivedGeneration(t, m, rs.Id) != gen { + t.Fatalf("stale callback changed the stored reset: %v %v", got, err) + } + }) +} - // An ordinary update that sets TRANSFERRING also invalidates the attempt. - if _, err := m.UpdateReceivedShare(ctx, user, reset, stateMask()); err != nil { +func TestOrdinaryUpdateCannotEnterOrLeaveTransferring(t *testing.T) { + forEachDialect(t, func(t *testing.T, m *mgr) { + ctx, user := ownerContext(t, "marie") + rs := storeReceived(t, m, ctx, user, "manual-transfer") + row := receivedRow(t, m, rs.Id.OpaqueId) + manual := &ocm.ReceivedShare{Id: rs.Id, State: ocm.ShareState_SHARE_STATE_TRANSFERRING, Hidden: true} + both := &field_mask.FieldMask{Paths: []string{"state", "hidden"}} + before, err := readReceivedProjection(m.db, row.ID) + if err != nil { t.Fatal(err) } - manual := &ocm.ReceivedShare{Id: rs.Id, State: ocm.ShareState_SHARE_STATE_TRANSFERRING} - manualUpdate, err := m.UpdateReceivedShare(ctx, user, manual, stateMask()) + var badRequest errtypes.BadRequest + if u, err := m.UpdateReceivedShare(ctx, user, manual, both); !errors.As(err, &badRequest) || u != nil { + t.Fatalf("ordinary entry receipt %v, error %v", u, err) + } + if got, err := readReceivedProjection(m.db, row.ID); err != nil || !before.equal(got) { + t.Fatalf("refused entry changed the projection: %v", err) + } + + // Older writers could leave a TRANSFERRING row without a generation. + setRow(t, m.db, row.ID, map[string]any{"state": model.OcmShareStateTransferring}) + before, err = readReceivedProjection(m.db, row.ID) if err != nil { t.Fatal(err) } - gen := receivedGeneration(t, m, rs.Id) - if u, err := m.CompleteReceivedShareTransfer(ctx, user, rs.Id, second.Generation, ocm.ShareState_SHARE_STATE_ACCEPTED); err != nil || u == nil || !proto.Equal(u.Before, manualUpdate.After) || !proto.Equal(u.After, manualUpdate.After) { - t.Fatalf("manual TRANSFERRING revived an old attempt: %v %v", u, err) + reset := &ocm.ReceivedShare{Id: rs.Id, State: ocm.ShareState_SHARE_STATE_PENDING, Hidden: true} + if u, err := m.UpdateReceivedShare(ctx, user, reset, both); !errors.Is(err, share.ErrTransferInProgress) || u != nil { + t.Fatalf("historical reservation reset receipt %v, error %v", u, err) + } + if got, err := readReceivedProjection(m.db, row.ID); err != nil || !before.equal(got) { + t.Fatalf("refused reset changed the projection: %v", err) + } + if u, err := m.UpdateReceivedShare(ctx, user, manual, stateMask()); err != nil || u == nil || u.StateChanged() || u.After.GetHidden() { + t.Fatalf("same-state receipt %v, error %v", u, err) + } + if u, err := m.UpdateReceivedShare(ctx, user, reset, &field_mask.FieldMask{Paths: []string{"hidden"}}); err != nil || u == nil || + u.After.GetState() != manual.State || !u.After.GetHidden() { + t.Fatalf("hidden-only receipt %v, error %v", u, err) } - if got := receivedGeneration(t, m, rs.Id); got != gen { - t.Fatalf("manual TRANSFERRING completion changed generation to %d, want %d", got, gen) + if got := receivedGeneration(t, m, rs.Id); got != before.row.TransferGeneration { + t.Fatalf("same-state or hidden-only update changed generation to %d", got) } }) } diff --git a/pkg/share/manager/sql/ocm_shares.go b/pkg/share/manager/sql/ocm_shares.go index 6e1fe2a5c58..bbe3b8ce91b 100644 --- a/pkg/share/manager/sql/ocm_shares.go +++ b/pkg/share/manager/sql/ocm_shares.go @@ -743,8 +743,7 @@ func nextTransferGeneration(current uint64) (uint64, error) { } // UpdateReceivedShare applies the masked fields in one transaction and -// returns the values read before and after. A state change invalidates the -// running transfer attempt, if any. +// returns the values read before and after. func (m *mgr) UpdateReceivedShare(ctx context.Context, user *userpb.User, s *ocm.ReceivedShare, fieldMask *field_mask.FieldMask) (*share.ReceivedShareUpdate, error) { updates, _, err := m.translateUpdateFieldMask(s, fieldMask) if err != nil { @@ -758,6 +757,15 @@ func (m *mgr) UpdateReceivedShare(ctx context.Context, user *userpb.User, s *ocm if err != nil { return err } + if state, ok := updates["state"]; ok && state != row.State { + // Only the transfer lifecycle can create or release a reservation. + if row.State == model.OcmShareStateTransferring { + return share.ErrTransferInProgress + } + if state == model.OcmShareStateTransferring { + return errtypes.BadRequest("cannot set transferring state directly") + } + } previous, err := readReceivedProjection(tx, row.ID) if err != nil { return err From 1c090ac00eb446f401d6e532488809020b53ee63 Mon Sep 17 00:00:00 2001 From: Mahdi Baghbani Date: Thu, 26 Nov 2026 13:14:30 +0000 Subject: [PATCH 6/8] fix(ocm): refuse directed DATATX decline Signed-off-by: Mahdi Baghbani --- .../ocmshareprovider/embedded_route_test.go | 315 +++++++++++++++++- pkg/ocm/share/contact.go | 8 + pkg/share/manager/sql/ocm_contact.go | 71 ++-- .../manager/sql/ocm_directed_actions_test.go | 151 +++++++++ 4 files changed, 519 insertions(+), 26 deletions(-) diff --git a/internal/grpc/services/ocmshareprovider/embedded_route_test.go b/internal/grpc/services/ocmshareprovider/embedded_route_test.go index df8c3b088b0..ec0b0c01536 100644 --- a/internal/grpc/services/ocmshareprovider/embedded_route_test.go +++ b/internal/grpc/services/ocmshareprovider/embedded_route_test.go @@ -20,11 +20,21 @@ package ocmshareprovider import ( "context" + "database/sql" "errors" + "fmt" + "io" + "net" "net/http" "net/http/httptest" "net/url" + "os" + "path/filepath" + "strconv" + "strings" + "sync" "testing" + "time" gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1" userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" @@ -32,6 +42,7 @@ import ( rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1" ocm "github.com/cs3org/go-cs3apis/cs3/sharing/ocm/v1beta1" datatx "github.com/cs3org/go-cs3apis/cs3/tx/v1beta1" + txservice "github.com/cs3org/reva/v3/internal/grpc/services/datatx" revagateway "github.com/cs3org/reva/v3/internal/grpc/services/gateway" httpauth "github.com/cs3org/reva/v3/internal/http/interceptors/auth" _ "github.com/cs3org/reva/v3/internal/http/interceptors/auth/credential/strategy/bearer" @@ -41,12 +52,19 @@ import ( "github.com/cs3org/reva/v3/internal/http/services/sciencemesh" "github.com/cs3org/reva/v3/pkg/appctx" "github.com/cs3org/reva/v3/pkg/auth/scope" + txdriver "github.com/cs3org/reva/v3/pkg/datatx" + txregistry "github.com/cs3org/reva/v3/pkg/datatx/manager/registry" + txjson "github.com/cs3org/reva/v3/pkg/datatx/repository/json" + "github.com/cs3org/reva/v3/pkg/errtypes" "github.com/cs3org/reva/v3/pkg/ocm/share" "github.com/cs3org/reva/v3/pkg/rhttp/router" _ "github.com/cs3org/reva/v3/pkg/share/cache/memory" "github.com/cs3org/reva/v3/pkg/token/manager/jwt" + "github.com/go-sql-driver/mysql" + "github.com/google/uuid" "google.golang.org/genproto/protobuf/field_mask" "google.golang.org/grpc" + "google.golang.org/protobuf/proto" ) type mountedGateway struct { @@ -65,6 +83,8 @@ type mountedEmbeddedPeers struct { provider *service datatxCalls int datatxResponse *datatx.CreateTransferResponse + datatxServer datatx.TxAPIServer + webdavURL string updateCalls int lookupOverride bool lookupResult *ocm.GetReceivedOCMShareResponse @@ -96,17 +116,24 @@ func (p *mountedEmbeddedPeers) UpdateReceivedOCMShare(ctx context.Context, req * } func (p *mountedEmbeddedPeers) GetInfoByDomain(context.Context, *ocmprovider.GetInfoByDomainRequest, ...grpc.CallOption) (*ocmprovider.GetInfoByDomainResponse, error) { + host, endpoint := "dest.example.org", "https://dest.example.org/dav" + if p.webdavURL != "" { + host, endpoint = p.webdavURL, p.webdavURL+"/dav" + } return &ocmprovider.GetInfoByDomainResponse{ Status: &rpc.Status{Code: rpc.Code_CODE_OK}, ProviderInfo: &ocmprovider.ProviderInfo{Services: []*ocmprovider.Service{{ - Host: "dest.example.org", - Endpoint: &ocmprovider.ServiceEndpoint{Type: &ocmprovider.ServiceType{Name: "webdav"}, Path: "https://dest.example.org/dav"}, + Host: host, + Endpoint: &ocmprovider.ServiceEndpoint{Type: &ocmprovider.ServiceType{Name: "webdav"}, Path: endpoint}, }}}, }, nil } -func (p *mountedEmbeddedPeers) CreateTransfer(context.Context, *datatx.CreateTransferRequest, ...grpc.CallOption) (*datatx.CreateTransferResponse, error) { +func (p *mountedEmbeddedPeers) CreateTransfer(ctx context.Context, req *datatx.CreateTransferRequest, _ ...grpc.CallOption) (*datatx.CreateTransferResponse, error) { p.datatxCalls++ + if p.datatxServer != nil { + return p.datatxServer.CreateTransfer(ctx, req) + } return p.datatxResponse, nil } @@ -140,6 +167,288 @@ func mountEmbeddedGateway(t *testing.T, e *emitEnv, tokenManagers map[string]map return client, peers } +type loopbackCopyDriver struct { + client *http.Client + starts, cancels, retries int + done chan struct{} + err error +} + +const loopbackCopyID = "loopback-copy" + +func (d *loopbackCopyDriver) CreateTransfer(_ context.Context, source, destination string) (*datatx.TxInfo, error) { + d.starts++ + if d.starts != 1 { + return nil, errors.New("unexpected second copy") + } + go func() { + defer close(d.done) + d.err = d.copy(source, destination) + }() + return &datatx.TxInfo{Id: &datatx.TxId{OpaqueId: loopbackCopyID}, Status: datatx.Status_STATUS_TRANSFER_NEW}, nil +} + +func (d *loopbackCopyDriver) copy(source, destination string) error { + resp, err := d.client.Get(source) + if err != nil { + return err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return fmt.Errorf("copy source returned %s", resp.Status) + } + target, err := url.Parse(destination) + if err != nil { + return err + } + target.Path, target.RawQuery = target.Query().Get("name"), "" + req, err := http.NewRequest(http.MethodPut, target.String(), resp.Body) + if err != nil { + return err + } + out, err := d.client.Do(req) + if err != nil { + return err + } + defer out.Body.Close() + if out.StatusCode != http.StatusCreated { + return fmt.Errorf("copy destination returned %s", out.Status) + } + return nil +} + +func (d *loopbackCopyDriver) GetTransferStatus(_ context.Context, id string) (*datatx.TxInfo, error) { + if id != loopbackCopyID || d.starts == 0 { + return nil, errors.New("unknown copy") + } + info := &datatx.TxInfo{Id: &datatx.TxId{OpaqueId: id}, Status: datatx.Status_STATUS_TRANSFER_IN_PROGRESS} + select { + case <-d.done: + info.Status = datatx.Status_STATUS_TRANSFER_COMPLETE + if d.err != nil { + info.Status = datatx.Status_STATUS_TRANSFER_FAILED + return info, d.err + } + default: + } + return info, nil +} + +func (d *loopbackCopyDriver) CancelTransfer(context.Context, string) (*datatx.TxInfo, error) { + d.cancels++ + return &datatx.TxInfo{}, errors.New("unexpected copy cancellation") +} + +func (d *loopbackCopyDriver) RetryTransfer(context.Context, string) (*datatx.TxInfo, error) { + d.retries++ + return &datatx.TxInfo{}, errors.New("unexpected copy retry") +} + +func TestMountedDirectedDeclineRefusesLiveDATATX(t *testing.T) { + t.Run("sqlite", func(t *testing.T) { checkMountedLiveDATATX(t, newEmitEnv(t)) }) + t.Run("mysql", func(t *testing.T) { + raw := os.Getenv("REVA_TEST_MYSQL") + if raw == "" { + t.Skip("disposable MySQL fixture is unavailable") + } + auth, addr, ok := strings.Cut(raw, "@") + if !ok { + t.Fatal("invalid REVA_TEST_MYSQL target") + } + dsn, err := mysql.ParseDSN(auth + "@tcp(" + addr + ")/") + if err != nil { + t.Fatal("invalid MySQL DSN") + } + host, portText, err := net.SplitHostPort(dsn.Addr) + if err != nil { + t.Fatal("invalid MySQL host and port") + } + port, err := strconv.Atoi(portText) + if err != nil { + t.Fatal("invalid MySQL port") + } + admin, err := sql.Open("mysql", dsn.FormatDSN()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = admin.Close() }) + name := "ocm_datatx_" + strings.ReplaceAll(uuid.NewString(), "-", "") + if _, err := admin.Exec("CREATE DATABASE " + name + " CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci"); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if _, err := admin.Exec("DROP DATABASE " + name); err != nil { + t.Errorf("drop disposable schema: %v", err) + } + }) + checkMountedLiveDATATX(t, newEmitEnvWithDatabase(t, map[string]any{ + "db_engine": "mysql", "db_host": host, "db_port": port, "db_name": name, + "db_username": dsn.User, "db_password": dsn.Passwd, + })) + }) +} + +func checkMountedLiveDATATX(t *testing.T, e *emitEnv) { + t.Helper() + const payload = "live DATATX copy" + destFile := filepath.Join(t.TempDir(), "doc.txt") + entered, release := make(chan struct{}), make(chan struct{}) + finish := sync.OnceFunc(func() { close(release) }) + mux := http.NewServeMux() + mux.HandleFunc("GET /source", func(w http.ResponseWriter, _ *http.Request) { + _, _ = io.WriteString(w, payload) + }) + mux.HandleFunc("PUT /dav/transfers/doc.txt", func(w http.ResponseWriter, req *http.Request) { + data, err := io.ReadAll(req.Body) + if err != nil || string(data) != payload { + w.WriteHeader(http.StatusBadRequest) + return + } + close(entered) + select { + case <-release: + case <-req.Context().Done(): + return + } + if err := os.WriteFile(destFile, data, 0600); err != nil { + w.WriteHeader(http.StatusInternalServerError) + return + } + w.WriteHeader(http.StatusCreated) + }) + peer := httptest.NewServer(mux) + t.Cleanup(peer.Close) + client := peer.Client() + client.Timeout = 20 * time.Second + driver := &loopbackCopyDriver{client: client, done: make(chan struct{})} + wait := func(done <-chan struct{}) { + t.Helper() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatal("copy did not reach the expected data step") + } + } + t.Cleanup(func() { + finish() + if driver.starts > 0 { + wait(driver.done) + } + }) + + const driverName = "directed-decline-loopback" + txregistry.Register(driverName, func(context.Context, map[string]any) (txdriver.Manager, error) { return driver, nil }) + t.Cleanup(func() { delete(txregistry.NewFuncs, driverName) }) + repoConfig := map[string]any{"file": filepath.Join(t.TempDir(), "transfers.json")} + tx, err := txservice.New(e.recip, map[string]any{ + "txdriver": driverName, "storagedriver": "json", + "storagedrivers": map[string]map[string]any{"json": repoConfig}, + }) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = tx.Close() }) + txAPI := tx.(datatx.TxAPIServer) + gw, peers := mountEmbeddedGateway(t, e, map[string]map[string]any{"jwt": {"secret": "datatx-route-test"}}) + peers.datatxServer, peers.webdavURL = txAPI, peer.URL + const actorToken = "test-copy-token" + e.recip = appctx.ContextSetToken(e.recip, actorToken) + recipient := appctx.ContextMustGetUser(e.recip) + recipient.Id.Type, recipient.Id.TenantId = userpb.UserType_USER_TYPE_PRIMARY, "test-tenant" + sibling := e.received(t, "legacy-first", false, ocm.AccessType_ACCESS_TYPE_REMOTE) + legacy := proto.CloneOf(sibling) + legacy.Id, legacy.RemoteShareId = nil, "legacy-live" + legacy.Protocols[0].GetWebdavOptions().Uri = peer.URL + "/source" + legacy.Protocols[0].GetWebdavOptions().AccessTypes = []ocm.AccessType{ocm.AccessType_ACCESS_TYPE_REMOTE, ocm.AccessType_ACCESS_TYPE_DATATX} + legacy, err = e.repo.StoreReceivedShare(e.recip, legacy) + if err != nil { + t.Fatal(err) + } + update := func(state ocm.ShareState, want rpc.Code) { + t.Helper() + res, err := gw.UpdateReceivedOCMShare(e.recip, &ocm.UpdateReceivedOCMShareRequest{ + Share: &ocm.ReceivedShare{Id: legacy.Id, State: state}, UpdateMask: &field_mask.FieldMask{Paths: []string{"state"}}, + }) + if err != nil || res.GetStatus().GetCode() != want { + t.Fatalf("update to %v: status %v, error %v, want %v", state, res.GetStatus(), err, want) + } + } + read := func(id *ocm.ShareId) *ocm.ReceivedShare { + t.Helper() + rs, err := e.repo.GetReceivedShare(e.recip, recipient, &ocm.ShareReference{Spec: &ocm.ShareReference_Id{Id: id}}) + if err != nil { + t.Fatal(err) + } + return rs + } + checkJob := func(want datatx.Status) { + t.Helper() + repo, err := txjson.New(e.recip, repoConfig) + if err != nil { + t.Fatal(err) + } + correlation, err := repo.GetTransfer(loopbackCopyID) + if err != nil { + t.Fatal(err) + } + if correlation.TxID != loopbackCopyID || correlation.ShareID != legacy.Id.OpaqueId || + !proto.Equal(correlation.UserID, recipient.Id) || correlation.SrcTargetURI != peer.URL+"/source" || + correlation.DestTargetURI != "http://"+actorToken+"@"+strings.TrimPrefix(peer.URL, "http://")+"?name=/dav/transfers/doc.txt" { + t.Fatal("persisted job correlation differs from the scheduled share and actor") + } + response, err := txAPI.GetTransferStatus(e.recip, &datatx.GetTransferStatusRequest{TxId: &datatx.TxId{OpaqueId: loopbackCopyID}}) + info := response.GetTxInfo() + if err != nil || response.GetStatus().GetCode() != rpc.Code_CODE_OK || + info.GetId().GetOpaqueId() != loopbackCopyID || !proto.Equal(info.GetShareId(), legacy.Id) || info.GetStatus() != want { + t.Fatalf("copy status %v, error %v, want %s for the original attempt", response, err, want) + } + if peers.datatxCalls != 1 || driver.starts != 1 || driver.cancels != 0 || driver.retries != 0 { + t.Fatalf("unexpected scheduling actions: dispatch=%d start=%d cancel=%d retry=%d", peers.datatxCalls, driver.starts, driver.cancels, driver.retries) + } + } + + siblingBefore := read(sibling.Id) + update(ocm.ShareState_SHARE_STATE_ACCEPTED, rpc.Code_CODE_OK) + wait(entered) + actions := e.repo.(share.DirectedShareActions) + refuse := func(state ocm.ShareState) { + t.Helper() + before := read(legacy.Id) + if before.State != state { + t.Fatalf("durable state %s, want %s", before.State, state) + } + checkJob(datatx.Status_STATUS_TRANSFER_IN_PROGRESS) + updates, err := actions.RejectReceivedOCMSharesFromSender(e.recip, recipient.Id, legacy.Creator) + var conflict errtypes.Conflict + if updates != nil || !errors.Is(err, share.ErrDataTransferStateUnavailable) || !errors.As(err, &conflict) { + t.Fatalf("directed action returned %d receipts and %v", len(updates), err) + } + if !proto.Equal(before, read(legacy.Id)) || !proto.Equal(siblingBefore, read(sibling.Id)) { + t.Fatal("refused action changed a durable projection") + } + if _, err := os.Stat(destFile); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("copy destination before release: %v", err) + } + checkJob(datatx.Status_STATUS_TRANSFER_IN_PROGRESS) + requireNotices(t, e.peer) + } + refuse(ocm.ShareState_SHARE_STATE_ACCEPTED) + e.svc.conf.DisableDataTxAcceptance = true + refuse(ocm.ShareState_SHARE_STATE_ACCEPTED) + update(ocm.ShareState_SHARE_STATE_PENDING, rpc.Code_CODE_OK) + update(ocm.ShareState_SHARE_STATE_ACCEPTED, rpc.Code_CODE_UNIMPLEMENTED) + refuse(ocm.ShareState_SHARE_STATE_PENDING) + e.svc.conf.DisableDataTxAcceptance = false + refuse(ocm.ShareState_SHARE_STATE_PENDING) + + finish() + wait(driver.done) + checkJob(datatx.Status_STATUS_TRANSFER_COMPLETE) + if data, err := os.ReadFile(destFile); err != nil || string(data) != payload { + t.Fatalf("destination contains %q, error %v", data, err) + } +} + func TestMountedEmbeddedShareProcessing(t *testing.T) { e := newEmitEnv(t) jwtConfig := map[string]any{"secret": "embedded-route-test"} diff --git a/pkg/ocm/share/contact.go b/pkg/ocm/share/contact.go index b12fa29ba47..399f5145f33 100644 --- a/pkg/ocm/share/contact.go +++ b/pkg/ocm/share/contact.go @@ -22,14 +22,22 @@ import ( "context" userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" + "github.com/cs3org/reva/v3/pkg/errtypes" ) +// ErrDataTransferStateUnavailable indicates that a directed decline cannot +// establish authoritative job state for a received DATATX projection. +var ErrDataTransferStateUnavailable = errtypes.Conflict("DATATX job state unavailable for directed decline") + // DirectedShareActions withdraws or rejects exact bound grants for an // authenticated local creator or recipient. // Historical grants without a complete binding remain available to ordinary // per-share operations. Each direction changes its eligible selection atomically // and returns receipts only after commit acknowledgment. CommitUnknownError // leaves the outcome unknown. A received selection with a transfer in progress is refused. +// Stored DATATX access also fences the entire incoming action, in any projection +// state, because the action has no scheduler interlock. This can block decline +// for never-started or terminal jobs. Ordinary per-share operations still apply. type DirectedShareActions interface { RemoveOCMSharesForRecipient(ctx context.Context, creator, recipient *userpb.UserId) ([]*ShareRemoval, error) RejectReceivedOCMSharesFromSender(ctx context.Context, recipient, sender *userpb.UserId) ([]*ReceivedShareUpdate, error) diff --git a/pkg/share/manager/sql/ocm_contact.go b/pkg/share/manager/sql/ocm_contact.go index 109e81313ab..6c854448ec3 100644 --- a/pkg/share/manager/sql/ocm_contact.go +++ b/pkg/share/manager/sql/ocm_contact.go @@ -30,6 +30,7 @@ import ( "github.com/cs3org/reva/v3/pkg/ocm/providerdomain" "github.com/cs3org/reva/v3/pkg/ocm/share" model "github.com/cs3org/reva/v3/pkg/share/manager/sql/model" + "google.golang.org/protobuf/proto" "gorm.io/gorm" ) @@ -132,10 +133,11 @@ func (m *mgr) RejectReceivedOCMSharesFromSender(ctx context.Context, recipient, check = commitCheck{} var selected []model.OcmReceivedShare senderAddress := sender.GetOpaqueId() + "@" + senderHost + activeStates := []model.OcmShareState{model.OcmShareStatePending, model.OcmShareStateAccepted, model.OcmShareStateTransferring} if err := forUpdate(tx). Where("initiator = ? AND share_with = ? AND share_with_idp = ? AND share_with_tenant = ? AND recipient_user_type = ? AND recipient_type = ?", senderAddress, recipient.GetOpaqueId(), recipient.GetIdp(), recipient.GetTenantId(), int32(recipient.GetType()), model.OcmShareTypeUser). - Where("state IN ?", []model.OcmShareState{model.OcmShareStatePending, model.OcmShareStateAccepted, model.OcmShareStateTransferring}). + Where("(state IN ? OR grant_key IS NOT NULL)", activeStates). Order("id").Find(&selected).Error; err != nil { return err } @@ -147,12 +149,19 @@ func (m *mgr) RejectReceivedOCMSharesFromSender(ctx context.Context, recipient, // The inherited text columns may match under a looser collation. continue } + active := slices.Contains(activeStates, row.State) key, err := share.GrantKey(senderHost, row.RemoteShareID) if err != nil || row.GrantKey == nil || *row.GrantKey != key { - return share.ErrGrantIdentityMismatch + if active { + return share.ErrGrantIdentityMismatch + } + continue } if !share.SupportedResourceType(convertToCS3SharedResourceType(row.ItemType)) { - return share.ErrInvalidResourceType + if active { + return share.ErrInvalidResourceType + } + continue } authorized = append(authorized, row) transferring = transferring || row.State == model.OcmShareStateTransferring @@ -162,7 +171,26 @@ func (m *mgr) RejectReceivedOCMSharesFromSender(ctx context.Context, recipient, if transferring { return share.ErrTransferInProgress } - if len(authorized) == 0 { + type eligibleProjection struct { + row model.OcmReceivedShare + before *ocm.ReceivedShare + } + var eligible []eligibleProjection + for _, row := range authorized { + protocols, err := protocolsTx(tx, row.ID) + if err != nil { + return err + } + before := convertToCS3OCMReceivedShare(&row, protocols) + // Ordinary state changes do not fence the scheduler. + if share.DataTransferProtocol(before) != nil { + return share.ErrDataTransferStateUnavailable + } + if slices.Contains(activeStates, row.State) { + eligible = append(eligible, eligibleProjection{row: row, before: before}) + } + } + if len(eligible) == 0 { return nil } @@ -171,36 +199,33 @@ func (m *mgr) RejectReceivedOCMSharesFromSender(ctx context.Context, recipient, Hidden bool TransferGeneration uint64 } - ids := make([]uint, 0, len(authorized)) - previous := make([]stateSnapshot, 0, len(authorized)) - expected := make([]stateSnapshot, 0, len(authorized)) - for _, row := range authorized { - protocols, err := protocolsTx(tx, row.ID) - if err != nil { - return err - } - before := convertToCS3OCMReceivedShare(&row, protocols) + ids := make([]uint, 0, len(eligible)) + previous := make([]stateSnapshot, 0, len(eligible)) + expected := make([]stateSnapshot, 0, len(eligible)) + for _, projection := range eligible { + row := projection.row previous = append(previous, stateSnapshot{row.State, row.Hidden, row.TransferGeneration}) if err := updateReceivedFields(tx, &row, map[string]any{ "state": model.OcmShareStateRejected, "hidden": true, "mtime": time.Now().Unix(), }); err != nil { return err } - applied, err := readReceivedProjection(tx, row.ID) - if err != nil { - return err + var applied model.OcmReceivedShare + result := tx.Find(&applied, row.ID) + if result.Error != nil { + return result.Error } - if applied == nil { + if result.RowsAffected == 0 { return share.ErrShareNotFound } - var appliedProtocols []*ocm.Protocol - for i := range applied.protocols { - appliedProtocols = append(appliedProtocols, convertToCS3Protocol(&applied.protocols[i])) + protocols := slices.Clone(projection.before.Protocols) + for i, protocol := range protocols { + protocols[i] = proto.CloneOf(protocol) } - after := convertToCS3OCMReceivedShare(&applied.row, appliedProtocols) + after := convertToCS3OCMReceivedShare(&applied, protocols) ids = append(ids, row.ID) - expected = append(expected, stateSnapshot{applied.row.State, applied.row.Hidden, applied.row.TransferGeneration}) - receipts = append(receipts, &share.ReceivedShareUpdate{Before: before, After: after}) + expected = append(expected, stateSnapshot{applied.State, applied.Hidden, applied.TransferGeneration}) + receipts = append(receipts, &share.ReceivedShareUpdate{Before: projection.before, After: after}) } check.observe = func(db *gorm.DB) (share.CommitObservation, error) { var observed []stateSnapshot diff --git a/pkg/share/manager/sql/ocm_directed_actions_test.go b/pkg/share/manager/sql/ocm_directed_actions_test.go index d014e2bcffb..787242b4663 100644 --- a/pkg/share/manager/sql/ocm_directed_actions_test.go +++ b/pkg/share/manager/sql/ocm_directed_actions_test.go @@ -345,6 +345,157 @@ func TestDirectedDeclineRefusesCorruptBinding(t *testing.T) { }) } +func TestDirectedDeclineRefusesStoredDataTransfer(t *testing.T) { + forEachDialect(t, func(t *testing.T, m *mgr) { + ctx := context.Background() + alice := recipient("alice") + alice.Id.TenantId = "Tenant" + bob := &userpb.UserId{OpaqueId: "bob", Idp: "remote.example.org:8443"} + other := &userpb.UserId{OpaqueId: "BOB", Idp: bob.Idp} + remote := ocm.AccessType_ACCESS_TYPE_REMOTE + datatx := ocm.AccessType_ACCESS_TYPE_DATATX + store := func(sender *userpb.UserId, id string, access ...ocm.AccessType) *ocm.ReceivedShare { + t.Helper() + rs := grantShare(alice, sender.Idp, id, file) + rs.Creator = sender + rs.Protocols[0].GetWebdavOptions().AccessTypes = access + return rs + } + projection := func(id *ocm.ShareId) *receivedProjection { + t.Helper() + row := receivedRow(t, m, id.OpaqueId) + got, err := readReceivedProjection(m.db, row.ID) + if err != nil || got == nil { + t.Fatalf("read projection %s: %v", id.OpaqueId, err) + } + return got + } + setState := func(id *ocm.ShareId, state ocm.ShareState) { + t.Helper() + rs := &ocm.ReceivedShare{Id: id, State: state} + if update, err := m.UpdateReceivedShare(ctx, alice, rs, stateMask()); err != nil || update == nil || update.After.GetState() != state { + t.Fatalf("ordinary update to %s: %v, %v", state, update, err) + } + } + withdraw := func(rs *ocm.ReceivedShare) { + t.Helper() + receipt, err := m.WithdrawReceivedGrant(ctx, &share.GrantWithdrawal{ + Origin: bob.Idp, RemoteShareID: rs.RemoteShareId, ResourceType: rs.SharedResourceType, + }) + if err != nil || receipt == nil || !receipt.Changed { + t.Fatalf("withdraw %s: %v, %v", rs.Id.OpaqueId, receipt, err) + } + } + + sibling := mustStore(t, m, store(bob, "sibling", remote)) + legacy := mustStore(t, m, store(bob, "legacy", datatx)) + writes := 0 + const callback = "test:track-directed-updates" + if err := m.db.Callback().Update().Before("gorm:update").Register(callback, func(tx *gorm.DB) { + if tx.Statement.Schema != nil && tx.Statement.Schema.Name == "OcmReceivedShare" { + writes++ + } + }); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = m.db.Callback().Update().Remove(callback) }) + refuse := func(t *testing.T, target *ocm.ShareId) { + t.Helper() + beforeSibling, beforeTarget := projection(sibling.Id), projection(target) + beforeWrites := writes + updates, err := m.RejectReceivedOCMSharesFromSender(ctx, alice.Id, bob) + if updates != nil || !errors.Is(err, share.ErrDataTransferStateUnavailable) { + t.Fatalf("directed decline returned %d receipts and %v", len(updates), err) + } + if writes != beforeWrites || !beforeSibling.equal(projection(sibling.Id)) || !beforeTarget.equal(projection(target)) { + t.Fatal("refused decline attempted a write or changed a projection") + } + } + setState(legacy.Id, ocm.ShareState_SHARE_STATE_ACCEPTED) + t.Run("accepted", func(t *testing.T) { refuse(t, legacy.Id) }) + setState(legacy.Id, ocm.ShareState_SHARE_STATE_PENDING) + t.Run("reset and repeated decline", func(t *testing.T) { + refuse(t, legacy.Id) + refuse(t, legacy.Id) + }) + setState(legacy.Id, ocm.ShareState_SHARE_STATE_REJECTED) + t.Run("rejected", func(t *testing.T) { refuse(t, legacy.Id) }) + + historical := mustStore(t, m, store(bob, "historical", datatx)) + setState(historical.Id, ocm.ShareState_SHARE_STATE_REJECTED) + if err := m.db.Model(&model.OcmReceivedShare{}).Where("id = ?", historical.Id.OpaqueId). + Update("grant_key", nil).Error; err != nil { + t.Fatal(err) + } + historicalBefore := projection(historical.Id) + + // The later cases supply the sole bound DATATX projection for the pair. + for _, tc := range []struct { + name string + embedded bool + state model.OcmShareState + }{ + {name: "remote plus DATATX in invalid state", state: model.OcmShareState(99)}, + {name: "embedded plus DATATX", embedded: true, state: model.OcmShareStatePending}, + } { + withdraw(legacy) + rs := store(bob, tc.name, remote, datatx) + if tc.embedded { + rs.SharedResourceType = ocm.SharedResourceType_SHARE_RESOURCE_TYPE_EMBEDDED + rs.Protocols = append(rs.Protocols, share.NewEmbeddedProtocol(`{"@graph":[]}`)) + } + legacy = mustStore(t, m, rs) + if err := m.db.Model(&model.OcmReceivedShare{}).Where("id = ?", legacy.Id.OpaqueId).Update("state", tc.state).Error; err != nil { + t.Fatal(err) + } + t.Run(tc.name, func(t *testing.T) { refuse(t, legacy.Id) }) + } + + t.Run("disjoint exact pair", func(t *testing.T) { + legacyBefore := projection(legacy.Id) + ordinary := mustStore(t, m, store(other, "remote", remote)) + webapp := store(other, "webapp") + webapp.Protocols = []*ocm.Protocol{share.NewWebappProtocol("https://remote.example.org/apps", "secret", nil, nil, nil, "", nil)} + webapp = mustStore(t, m, webapp) + setState(ordinary.Id, ocm.ShareState_SHARE_STATE_ACCEPTED) + inactive := mustStore(t, m, store(other, "inactive", remote)) + setState(inactive.Id, ocm.ShareState_SHARE_STATE_REJECTED) + inactiveBefore := projection(inactive.Id) + updates, err := m.RejectReceivedOCMSharesFromSender(ctx, alice.Id, other) + if err != nil || len(updates) != 2 { + t.Fatalf("ordinary decline returned %d receipts and %v", len(updates), err) + } + for i, rs := range []*ocm.ReceivedShare{ordinary, webapp} { + after := updates[i].After + row := projection(rs.Id).row + if !proto.Equal(after.Id, rs.Id) || !updates[i].StateChanged() || !after.Hidden || + after.State != ocm.ShareState_SHARE_STATE_REJECTED || !row.Hidden || row.State != model.OcmShareStateRejected { + t.Fatalf("unexpected decline for %s", rs.Id.OpaqueId) + } + } + beforeProtocol := updates[0].Before.Protocols[0].GetWebdavOptions() + afterProtocol := updates[0].After.Protocols[0].GetWebdavOptions() + beforeProtocol.Uri = "https://changed.example.org" + if afterProtocol.Uri != ordinary.Protocols[0].GetWebdavOptions().Uri { + t.Fatal("editing the before receipt changed the after protocol") + } + updates, err = m.RejectReceivedOCMSharesFromSender(ctx, alice.Id, other) + if updates != nil || err != nil { + t.Fatalf("empty decline returned %d receipts and %v", len(updates), err) + } + if !legacyBefore.equal(projection(legacy.Id)) || !inactiveBefore.equal(projection(inactive.Id)) { + t.Fatal("decline touched a disjoint or inactive row") + } + }) + withdraw(legacy) + updates, err := m.RejectReceivedOCMSharesFromSender(ctx, alice.Id, bob) + if err != nil || len(updates) != 1 || !proto.Equal(updates[0].After.Id, sibling.Id) || + !historicalBefore.equal(projection(historical.Id)) { + t.Fatalf("incomplete binding affected decline: %d receipts, %v", len(updates), err) + } + }) +} + func TestDirectedBatchesAcrossBindBoundary(t *testing.T) { const limit = 500 for _, direction := range []string{"outgoing", "incoming"} { From 2907fb8aa318fc98395d1c4e1dc329d18018dfb8 Mon Sep 17 00:00:00 2001 From: Mahdi Baghbani Date: Thu, 26 Nov 2026 13:29:13 +0000 Subject: [PATCH 7/8] test(ocm): verify directed rollback before retry Signed-off-by: Mahdi Baghbani --- .../sql/ocm_directed_concurrency_test.go | 65 ++++++++++++++++--- 1 file changed, 56 insertions(+), 9 deletions(-) diff --git a/pkg/share/manager/sql/ocm_directed_concurrency_test.go b/pkg/share/manager/sql/ocm_directed_concurrency_test.go index e118c5ebe4a..04fea072dd1 100644 --- a/pkg/share/manager/sql/ocm_directed_concurrency_test.go +++ b/pkg/share/manager/sql/ocm_directed_concurrency_test.go @@ -14,6 +14,8 @@ import ( "context" dbsql "database/sql" "errors" + "fmt" + "reflect" "slices" "sync" "sync/atomic" @@ -133,11 +135,30 @@ func TestDirectedTransactionConcurrentSelectionAndRetry(t *testing.T) { } } var injected atomic.Bool + firstWriteFailed := make(chan error, 1) + var outgoingBefore model.OcmShare + var incomingBefore model.OcmReceivedShare if mode == "retry" { + operation, table := "update", "ocm_received_shares" + if direction == "outgoing" { + operation, table = "delete", "ocm_shares" + if err := writer.db.WithContext(ctx).Where("id = ?", original).Take(&outgoingBefore).Error; err != nil { + t.Fatal(err) + } + } else { + incomingBefore = receivedRow(t, writer, original) + } callback := func(tx *gorm.DB) { - if injected.CompareAndSwap(false, true) { - tx.AddError(errors.New("database is locked: injected retryable failure after mutation")) + if tx.Statement.Table != table || injected.Load() { + return } + if tx.Error != nil || tx.RowsAffected != 1 { + firstWriteFailed <- fmt.Errorf("first %s on %s affected %d rows (want 1), error %v", operation, table, tx.RowsAffected, tx.Error) + tx.Error = errors.New("unexpected first directed write result") + return + } + injected.Store(true) + tx.AddError(errors.New("database is locked: injected retryable failure after mutation")) } if direction == "outgoing" { err = m.db.Callback().Delete().After("gorm:delete").Register("test:retry-directed-delete", callback) @@ -177,20 +198,33 @@ func TestDirectedTransactionConcurrentSelectionAndRetry(t *testing.T) { for range done { } }() + var earlyAction *result + var rollbackErr error select { case <-gate.reached: case action := <-done: + earlyAction = &action select { - case err := <-gate.rollbackFailed: - t.Fatalf("rollback before retry barrier: %v", err) + case rollbackErr = <-gate.rollbackFailed: default: - t.Fatalf("action returned before %s barrier: error %v, receipt IDs %v", mode, action.err, action.ids) } - case err := <-gate.rollbackFailed: - t.Fatalf("rollback before retry barrier: %v", err) + case err := <-firstWriteFailed: + t.Fatal(err) + case rollbackErr = <-gate.rollbackFailed: case <-ctx.Done(): t.Fatal("transaction did not reach barrier") } + select { + case err := <-firstWriteFailed: + t.Fatal(err) + default: + } + if rollbackErr != nil { + t.Fatalf("rollback before retry barrier: %v", rollbackErr) + } + if earlyAction != nil { + t.Fatalf("action returned before %s barrier: error %v, receipt IDs %v", mode, earlyAction.err, earlyAction.ids) + } token := direction + mode + "later" if mode == "commit" { // The action cannot commit until a real competing write @@ -233,8 +267,21 @@ func TestDirectedTransactionConcurrentSelectionAndRetry(t *testing.T) { var later string var writerErr error if mode == "retry" { - // The first attempt has rolled back. Commit the new - // grant before the action can select again. + if !injected.Load() { + t.Fatal("rollback barrier reached without a successful first directed write") + } + if direction == "outgoing" { + var restored model.OcmShare + if err := writer.db.WithContext(ctx).Where("id = ?", original).Take(&restored).Error; err != nil { + t.Fatalf("read original outgoing grant after rollback: %v", err) + } + if !reflect.DeepEqual(restored, outgoingBefore) { + t.Fatal("original outgoing grant changed after rollback") + } + } else if restored := receivedRow(t, writer, original); !reflect.DeepEqual(restored, incomingBefore) { + t.Fatal("original incoming grant changed after rollback") + } + // The new grant must be visible when the action selects again. later, writerErr = store(writer, token, nil) release() } From 6fdbe27cde89fbb584f97f9964252865a9675136 Mon Sep 17 00:00:00 2001 From: Mahdi Baghbani Date: Thu, 26 Nov 2026 19:45:44 +0000 Subject: [PATCH 8/8] fix(ocm): recover unstarted SQL transfers Signed-off-by: Mahdi Baghbani --- pkg/share/manager/sql/model/model.go | 3 + pkg/share/manager/sql/ocm_commit_test.go | 129 ++++++++++++++++++++- pkg/share/manager/sql/ocm_identity.go | 6 +- pkg/share/manager/sql/ocm_receipts_test.go | 16 +++ pkg/share/manager/sql/ocm_shares.go | 37 +++++- 5 files changed, 180 insertions(+), 11 deletions(-) diff --git a/pkg/share/manager/sql/model/model.go b/pkg/share/manager/sql/model/model.go index 327e1ad59f1..485f86af81f 100644 --- a/pkg/share/manager/sql/model/model.go +++ b/pkg/share/manager/sql/model/model.go @@ -270,6 +270,9 @@ type OcmReceivedShare struct { // TransferGeneration grows on every transfer start and state change, so // that the completion of an older attempt cannot match a later one. TransferGeneration uint64 `gorm:"not null;default:0"` + // TransferAttempt identifies the start that set TRANSFERRING, so that + // only that start can release it. Older rows have none. + TransferAttempt *string `gorm:"size:36"` } // OcmReceivedShareProtocol represents the protocol used to access an OCM share received from a remote user. diff --git a/pkg/share/manager/sql/ocm_commit_test.go b/pkg/share/manager/sql/ocm_commit_test.go index 32e19274a0f..b2f362180f2 100644 --- a/pkg/share/manager/sql/ocm_commit_test.go +++ b/pkg/share/manager/sql/ocm_commit_test.go @@ -197,6 +197,8 @@ func TestUnacknowledgedCommitsObserveTheExactProjection(t *testing.T) { compete func(t *testing.T, db *gorm.DB, remote string) // generation is logged with an unknown outcome. generation bool + // release is one write after the fault that undoes an applied start. + release bool } stored := func(t *testing.T, m *mgr, remote string) (*ocm.ReceivedShare, uint64) { return mustStore(t, m, grantShare(marie, "a.example.org", remote, file)), 0 @@ -243,6 +245,7 @@ func TestUnacknowledgedCommitsObserveTheExactProjection(t *testing.T) { setRow(t, db, rowOf(t, db, remote), map[string]any{"state": model.OcmShareStateTransferring, "transfer_generation": 1, "mtime": 1}) }, generation: true, + release: true, }, { name: "complete transfer", @@ -333,8 +336,12 @@ func TestUnacknowledgedCommitsObserveTheExactProjection(t *testing.T) { if got || !errors.As(err, &unknown) || !errors.Is(err, share.ErrCommitUnknown) || unknown.Observed != tc.observed { t.Fatalf("receipt=%t err=%v", got, err) } - if p.commits.Load() != 1 || p.writes.Load() != 0 { - t.Fatalf("after an unacknowledged commit: commits %d, writes %d", p.commits.Load(), p.writes.Load()) + wantWrites := int32(0) + if o.release { + wantWrites = 1 + } + if p.commits.Load() != 1 || p.writes.Load() != wantWrites { + t.Fatalf("after an unacknowledged commit: commits %d, writes %d, want 1 and %d", p.commits.Load(), p.writes.Load(), wantWrites) } if p.reads.Load() == 0 { t.Fatal("no reconciliation read") @@ -355,8 +362,10 @@ func TestUnacknowledgedCommitsObserveTheExactProjection(t *testing.T) { t.Fatalf("log holds share data: %s", logs) } p.failRead = false - if o.done(t, other(t, cfg), remote) != tc.durable { - t.Fatalf("durable change %t, want %t", !tc.durable, tc.durable) + // A start whose own commit applied is released; a competing one is not. + durable := tc.durable && !(o.release && tc.apply) + if o.done(t, other(t, cfg), remote) != durable { + t.Fatalf("durable change %t, want %t", !durable, durable) } }) } @@ -365,6 +374,118 @@ func TestUnacknowledgedCommitsObserveTheExactProjection(t *testing.T) { } } +// A start without a commit acknowledgment returns no receipt, so no transfer +// runs for it. Only a reservation that still holds its own attempt is released. +func TestUnacknowledgedStartReleasesOnlyItsOwnReservation(t *testing.T) { + marie := recipient("marie") + foreign := "foreign-attempt" + for _, tc := range []struct { + name string + apply bool + between func(t *testing.T, db *gorm.DB, id uint, cancel context.CancelFunc) + failRelease bool + observed share.CommitObservation + released bool + attempt *string // the attempt a held reservation keeps, if not its own + alias string + prior model.OcmShareState + }{ + {name: "applied", apply: true, observed: share.CommitObservedRequested, released: true, prior: model.OcmShareStateRejected}, + {name: "applied then unrelated field changed", apply: true, between: func(t *testing.T, db *gorm.DB, id uint, _ context.CancelFunc) { + setRow(t, db, id, map[string]any{"alias": "kept"}) + }, observed: share.CommitObservedOther, released: true, alias: "kept"}, + {name: "applied then caller canceled", apply: true, between: func(_ *testing.T, _ *gorm.DB, _ uint, cancel context.CancelFunc) { + cancel() + }, observed: share.CommitObservedRequested, released: true}, + {name: "applied then no attempt", apply: true, between: func(t *testing.T, db *gorm.DB, id uint, _ context.CancelFunc) { + if err := db.Model(&model.OcmReceivedShare{}).Where("id = ?", id).Update("transfer_attempt", nil).Error; err != nil { + t.Fatal(err) + } + }, observed: share.CommitObservedOther}, + {name: "competing start with the same generation", between: func(t *testing.T, db *gorm.DB, id uint, _ context.CancelFunc) { + setRow(t, db, id, map[string]any{"state": model.OcmShareStateTransferring, "transfer_generation": 1, "transfer_attempt": foreign}) + }, observed: share.CommitObservedOther, attempt: &foreign}, + {name: "release fails", apply: true, failRelease: true, observed: share.CommitObservedRequested}, + } { + t.Run(tc.name, func(t *testing.T) { + forEachDialectConfig(t, func(t *testing.T, cfg map[string]any) { + m := openOCMManager(t, cfg) + remote := strings.ReplaceAll("release-"+tc.name, " ", "-") + rs := mustStore(t, m, grantShare(marie, "a.example.org", remote, file)) + id := rowOf(t, m.db, remote) + if tc.prior != model.OcmShareStatePending { + setRow(t, m.db, id, map[string]any{"state": tc.prior}) + } + var before model.OcmReceivedShare + if err := m.db.Where("id = ?", id).Take(&before).Error; err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + p := &commitFault{apply: tc.apply} + if tc.between != nil { + p.between = func() { tc.between(t, other(t, cfg), id, cancel) } + } + withCommitFault(t, m, p) + if tc.failRelease { + if err := m.db.Callback().Update().Before("gorm:update").Register("test:fail-release", func(tx *gorm.DB) { + if p.faulted.Load() { + _ = tx.AddError(errors.New("release write failed")) + } + }); err != nil { + t.Fatal(err) + } + } + p.armed.Store(true) + got, err := m.StartReceivedShareTransfer(ctx, marie, &ocm.ReceivedShare{Id: rs.Id}, stateMask()) + var unknown *share.CommitUnknownError + if got != nil || !errors.As(err, &unknown) || !errors.Is(err, share.ErrCommitUnknown) || unknown.Observed != tc.observed { + t.Fatalf("receipt %v, error %v, want commit unknown (%s)", got, err, tc.observed) + } + // One start commit, never repeated, and at most one release statement. + wantWrites := int32(1) + if tc.failRelease { + wantWrites = 0 + } + if p.commits.Load() != 1 || p.writes.Load() != wantWrites { + t.Fatalf("commits %d, writes %d, want 1 and %d", p.commits.Load(), p.writes.Load(), wantWrites) + } + + var row model.OcmReceivedShare + if err := other(t, cfg).Where("id = ?", id).Take(&row).Error; err != nil { + t.Fatal(err) + } + if row.TransferGeneration != 1 || row.Alias != tc.alias { + t.Fatalf("generation %d, alias %q, want 1 and %q", row.TransferGeneration, row.Alias, tc.alias) + } + if tc.released { + if row.State != before.State || row.State != tc.prior || row.TransferAttempt != nil { + t.Fatalf("released row state %v attempt %v, want %v and none", row.State, row.TransferAttempt, before.State) + } + next, err := m.StartReceivedShareTransfer(context.Background(), marie, &ocm.ReceivedShare{Id: rs.Id}, stateMask()) + if err != nil || next.Generation != 2 { + t.Fatalf("next start %v %v, want generation 2", next, err) + } + return + } + switch { + case row.State != model.OcmShareStateTransferring: + t.Fatalf("held row state %v", row.State) + case tc.attempt != nil && (row.TransferAttempt == nil || *row.TransferAttempt != *tc.attempt): + t.Fatalf("held row attempt %v, want %s", row.TransferAttempt, *tc.attempt) + case tc.attempt == nil && tc.failRelease && row.TransferAttempt == nil: + t.Fatal("held row lost its own attempt") + case tc.attempt == nil && !tc.failRelease && row.TransferAttempt != nil: + t.Fatalf("tokenless held row has attempt %s", *row.TransferAttempt) + } + if _, err := m.StartReceivedShareTransfer(context.Background(), marie, &ocm.ReceivedShare{Id: rs.Id}, stateMask()); !errors.Is(err, share.ErrTransferInProgress) { + t.Fatalf("held reservation admitted another start: %v", err) + } + }) + }) + } +} + // An older row of the same grant and user is not the row a failed creation // allocated, so it is not its requested state. func TestUnacknowledgedCreateIgnoresAnOlderRowOfTheGrant(t *testing.T) { diff --git a/pkg/share/manager/sql/ocm_identity.go b/pkg/share/manager/sql/ocm_identity.go index 89c0d776d4b..8281f60fdd0 100644 --- a/pkg/share/manager/sql/ocm_identity.go +++ b/pkg/share/manager/sql/ocm_identity.go @@ -142,12 +142,12 @@ func (p *receivedProjection) equal(q *receivedProjection) bool { return p == q } a, b := p.row, q.row - if a.ID != b.ID || a.RecipientUserType != b.RecipientUserType || !equalGrantKey(a.GrantKey, b.GrantKey) || a.RemoteShareID != b.RemoteShareID || a.Name != b.Name || + if a.ID != b.ID || a.RecipientUserType != b.RecipientUserType || !equalOptionalString(a.GrantKey, b.GrantKey) || a.RemoteShareID != b.RemoteShareID || a.Name != b.Name || a.ItemType != b.ItemType || a.ShareWith != b.ShareWith || a.ShareWithIdp != b.ShareWithIdp || a.ShareWithTenant != b.ShareWithTenant || a.Owner != b.Owner || a.Initiator != b.Initiator || a.Ctime != b.Ctime || a.Mtime != b.Mtime || !equalNullTime(a.Expiration, b.Expiration) || a.RecipientType != b.RecipientType || a.State != b.State || a.Alias != b.Alias || a.Hidden != b.Hidden || - a.TransferGeneration != b.TransferGeneration || a.DeletedAt.Valid != b.DeletedAt.Valid || + a.TransferGeneration != b.TransferGeneration || !equalOptionalString(a.TransferAttempt, b.TransferAttempt) || a.DeletedAt.Valid != b.DeletedAt.Valid || len(p.protocols) != len(q.protocols) { return false } @@ -163,7 +163,7 @@ func (p *receivedProjection) equal(q *receivedProjection) bool { return true } -func equalGrantKey(a, b *string) bool { +func equalOptionalString(a, b *string) bool { return (a == nil) == (b == nil) && (a == nil || *a == *b) } diff --git a/pkg/share/manager/sql/ocm_receipts_test.go b/pkg/share/manager/sql/ocm_receipts_test.go index ad00e0858c4..1d0f6178b72 100644 --- a/pkg/share/manager/sql/ocm_receipts_test.go +++ b/pkg/share/manager/sql/ocm_receipts_test.go @@ -559,6 +559,16 @@ func TestTransferAttemptLifecycle(t *testing.T) { if got := receivedGeneration(t, m, rs.Id); got != start.Generation { t.Fatalf("wrong generation completion changed generation to %d, want %d", got, start.Generation) } + attemptOf := func() *string { + var row model.OcmReceivedShare + if err := m.db.Where("id = ?", rs.Id.OpaqueId).Take(&row).Error; err != nil { + t.Fatal(err) + } + return row.TransferAttempt + } + if attemptOf() == nil { + t.Fatal("running attempt has no attempt ID") + } const beforeMtime = 946684800 if err := m.db.Model(&model.OcmReceivedShare{}).Where("id = ?", rs.Id.OpaqueId). Update("mtime", beforeMtime).Error; err != nil { @@ -578,6 +588,9 @@ func TestTransferAttemptLifecycle(t *testing.T) { if !u.After.Hidden || len(u.After.Protocols) != len(rs.Protocols) { t.Fatalf("completion changed hidden/protocols: %v", u.After) } + if a := attemptOf(); a != nil { + t.Fatalf("finished transfer kept attempt ID %s", *a) + } if duplicate, err := m.CompleteReceivedShareTransfer(ctx, user, rs.Id, start.Generation, ocm.ShareState_SHARE_STATE_ACCEPTED); err != nil || duplicate == nil || !proto.Equal(duplicate.Before, u.After) || !proto.Equal(duplicate.After, u.After) { t.Fatalf("duplicate completion: %v %v", duplicate, err) } @@ -604,6 +617,9 @@ func TestTransferAttemptLifecycle(t *testing.T) { !proto.Equal(u.Before, second.Share) || !proto.Equal(u.After, second.Share) { t.Fatalf("stale callback completed a newer attempt: %v %v", u, err) } + if attemptOf() == nil { + t.Fatal("stale callback cleared the attempt ID of a newer attempt") + } u, err = m.CompleteReceivedShareTransfer(ctx, user, rs.Id, second.Generation, ocm.ShareState_SHARE_STATE_ACCEPTED) if err != nil || u == nil || !proto.Equal(u.Before, second.Share) || u.After.GetState() != ocm.ShareState_SHARE_STATE_ACCEPTED { diff --git a/pkg/share/manager/sql/ocm_shares.go b/pkg/share/manager/sql/ocm_shares.go index bbe3b8ce91b..31594539ebe 100644 --- a/pkg/share/manager/sql/ocm_shares.go +++ b/pkg/share/manager/sql/ocm_shares.go @@ -39,6 +39,7 @@ import ( "github.com/cs3org/reva/v3/pkg/ocm/share" model "github.com/cs3org/reva/v3/pkg/share/manager/sql/model" "github.com/cs3org/reva/v3/pkg/utils/cfg" + "github.com/google/uuid" "github.com/pkg/errors" "google.golang.org/genproto/protobuf/field_mask" "google.golang.org/protobuf/proto" @@ -836,6 +837,8 @@ func (m *mgr) StartReceivedShareTransfer(ctx context.Context, user *userpb.User, } var receipt share.TransferStart var check commitCheck + attemptID := uuid.NewString() + var prior model.OcmShareState err = m.transact(ctx, "start_transfer", func(tx *gorm.DB) error { check = commitCheck{} row, _, err := lockReceived(tx, user, s.Id) @@ -856,8 +859,10 @@ func (m *mgr) StartReceivedShareTransfer(ctx context.Context, user *userpb.User, if err != nil { return err } + prior = row.State attempt := maps.Clone(updates) attempt["transfer_generation"] = gen + attempt["transfer_attempt"] = attemptID if err := tx.Model(&model.OcmReceivedShare{}).Where("id = ?", row.ID).Updates(attempt).Error; err != nil { return err } @@ -874,14 +879,37 @@ func (m *mgr) StartReceivedShareTransfer(ctx context.Context, user *userpb.User, receipt = share.TransferStart{Share: after, Generation: gen} return nil }, &check) + var unknown *share.CommitUnknownError + if errors.As(err, &unknown) { + m.releaseUnstartedTransfer(ctx, user, check.shareID, check.generation, attemptID, prior) + } if err != nil { return nil, err } return &receipt, nil } -// CompleteReceivedShareTransfer writes the final state and mtime only, and -// only while the same attempt is still running. +// The start returned no receipt, so this attempt never reached the copy driver. +func (m *mgr) releaseUnstartedTransfer(ctx context.Context, user *userpb.User, id uint, gen uint64, attemptID string, prior model.OcmShareState) { + if id == 0 || gen == 0 { + return + } + rctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), recoveryTimeout) + defer cancel() + res := m.db.WithContext(rctx).Model(&model.OcmReceivedShare{}). + Where("id = ? AND share_with = ? AND state = ? AND transfer_generation = ? AND transfer_attempt = ?", + id, user.Id.OpaqueId, model.OcmShareStateTransferring, gen, attemptID). + UpdateColumns(map[string]any{"state": prior, "transfer_attempt": nil}) + e := appctx.GetLogger(ctx).Warn().Uint("share_id", id).Uint64("transfer_generation", gen) + if res.Error != nil { + e.Msg("could not confirm transfer reservation release") + return + } + e.Int64("released", res.RowsAffected).Msg("unacknowledged transfer start checked for release") +} + +// CompleteReceivedShareTransfer writes the final state and mtime and clears +// the attempt ID, only while the same attempt is still running. func (m *mgr) CompleteReceivedShareTransfer(ctx context.Context, user *userpb.User, id *ocm.ShareId, generation uint64, state ocm.ShareState) (*share.ReceivedShareUpdate, error) { shareID, err := strconv.Atoi(id.GetOpaqueId()) if err != nil { @@ -906,8 +934,9 @@ func (m *mgr) CompleteReceivedShareTransfer(ctx context.Context, user *userpb.Us Where("id = ? AND share_with = ? AND state = ? AND transfer_generation = ?", shareID, user.Id.OpaqueId, model.OcmShareStateTransferring, generation). Updates(map[string]any{ - "state": convertFromCS3OCMShareState(state), - "mtime": time.Now().Unix(), + "state": convertFromCS3OCMShareState(state), + "mtime": time.Now().Unix(), + "transfer_attempt": nil, }) if result.Error != nil { return result.Error