From c3c2a8b99cca2461b93c2ec34977587cebfc90a9 Mon Sep 17 00:00:00 2001 From: Pascal Bleser Date: Wed, 11 Nov 2026 00:39:09 +0100 Subject: [PATCH 1/2] fix(graph): succeed when unassigning tags a resource doesn't have Removing a tag that the resource doesn't have failed with 400 and a message about assigning tags ("no new tags in createtagsrequest or maximum reached"). The tags of the resource are then already as requested, so it now succeeds instead, without writing the unchanged tags back. The TagsRemoved event is published in that case too, so that the search index drops tags that it has but the resource doesn't, which could otherwise only be removed by assigning them first. A request without any tags is still rejected with 400, now before looking up the resource. The log entries of the request now carry the requested resource id and the tags, and a failure to store the tags logs the status of the storage. The log message for a failed TagsRemoved event no longer calls it TagsAdded. Assisted-by: Claude Code:claude-opus-5-5 --- services/graph/pkg/service/v0/tags.go | 58 +++--- .../pkg/service/v0/tags_unassign_test.go | 176 ++++++++++++++++++ .../acceptance/features/apiSpaces/tag.feature | 16 ++ 3 files changed, 228 insertions(+), 22 deletions(-) create mode 100644 services/graph/pkg/service/v0/tags_unassign_test.go diff --git a/services/graph/pkg/service/v0/tags.go b/services/graph/pkg/service/v0/tags.go index 1a459e8962..27a71725a3 100644 --- a/services/graph/pkg/service/v0/tags.go +++ b/services/graph/pkg/service/v0/tags.go @@ -161,16 +161,30 @@ func (g Graph) UnassignTags(w http.ResponseWriter, r *http.Request) { return } + // A request without any tags is treated as malformed. That is a choice: + // as it asks to remove nothing, succeeding with 200 or 204 would be + // defensible too, but an empty list is more likely a client bug than + // intended. + if len(unassignment.Tags) == 0 { + errorcode.InvalidRequest.Render(w, r, http.StatusBadRequest, "no tags in tag unassignment request") + return + } + + logger := g.logger.SubloggerWithRequestID(ctx).With(). + Str("resourceID", unassignment.ResourceId). + Strs("tags", unassignment.Tags). + Logger() + rid, err := storagespace.ParseID(unassignment.ResourceId) if err != nil { - g.logger.Debug().Err(err).Msg("could not parse resourceId") + logger.Debug().Err(err).Msg("could not parse resourceId") errorcode.InvalidRequest.Render(w, r, http.StatusBadRequest, "invalid resourceId") return } client, err := g.gatewaySelector.Next() if err != nil { - g.logger.Error().Err(err).Msg("error selecting next gateway client") + logger.Error().Err(err).Msg("error selecting next gateway client") w.WriteHeader(http.StatusInternalServerError) return } @@ -178,7 +192,7 @@ func (g Graph) UnassignTags(w http.ResponseWriter, r *http.Request) { Ref: &provider.Reference{ResourceId: &rid}, }) if err != nil { - g.logger.Error().Err(err).Msg("error stating file") + logger.Error().Err(err).Msg("error stating file") w.WriteHeader(http.StatusInternalServerError) return } @@ -193,14 +207,14 @@ func (g Graph) UnassignTags(w http.ResponseWriter, r *http.Request) { pm := sres.GetInfo().GetPermissionSet() if pm == nil { - g.logger.Error().Err(err).Msg("no permissionset on file") + logger.Error().Msg("no permissionset on file") w.WriteHeader(http.StatusInternalServerError) return } // it says we need "write access" to set tags. One of those should do if !pm.InitiateFileUpload && !pm.CreateContainer { - g.logger.Info().Msg("no permission to create a tag") + logger.Info().Msg("no permission to remove a tag") w.WriteHeader(http.StatusForbidden) return } @@ -210,24 +224,24 @@ func (g Graph) UnassignTags(w http.ResponseWriter, r *http.Request) { currentTags = m["tags"] } + // Removing tags that the resource doesn't have is not an error: the result + // is the same, and the event below still goes out, so that the search + // index drops tags it may have although the resource doesn't. allTags := tags.New(currentTags) - if !allTags.Remove(unassignment.Tags...) { - errorcode.InvalidRequest.Render(w, r, http.StatusBadRequest, "no new tags in createtagsrequest or maximum reached") - return - } - - resp, err := client.SetArbitraryMetadata(ctx, &provider.SetArbitraryMetadataRequest{ - Ref: &provider.Reference{ResourceId: &rid}, - ArbitraryMetadata: &provider.ArbitraryMetadata{ - Metadata: map[string]string{ - "tags": allTags.AsList(), + if allTags.Remove(unassignment.Tags...) { + resp, err := client.SetArbitraryMetadata(ctx, &provider.SetArbitraryMetadataRequest{ + Ref: &provider.Reference{ResourceId: &rid}, + ArbitraryMetadata: &provider.ArbitraryMetadata{ + Metadata: map[string]string{ + "tags": allTags.AsList(), + }, }, - }, - }) - if err != nil || resp.GetStatus().GetCode() != rpc.Code_CODE_OK { - g.logger.Error().Err(err).Msg("error setting tags") - w.WriteHeader(http.StatusInternalServerError) - return + }) + if err != nil || resp.GetStatus().GetCode() != rpc.Code_CODE_OK { + logger.Error().Err(err).Interface("status", resp.GetStatus()).Msg("error setting tags") + w.WriteHeader(http.StatusInternalServerError) + return + } } if g.eventsPublisher != nil { @@ -241,7 +255,7 @@ func (g Graph) UnassignTags(w http.ResponseWriter, r *http.Request) { Executant: revaCtx.ContextMustGetUser(r.Context()).Id, } if err := events.Publish(ctx, g.eventsPublisher, ev); err != nil { - g.logger.Error().Err(err).Msg("Failed to publish TagsAdded event") + logger.Error().Err(err).Msg("Failed to publish TagsRemoved event") } } } diff --git a/services/graph/pkg/service/v0/tags_unassign_test.go b/services/graph/pkg/service/v0/tags_unassign_test.go new file mode 100644 index 0000000000..21b6fe3127 --- /dev/null +++ b/services/graph/pkg/service/v0/tags_unassign_test.go @@ -0,0 +1,176 @@ +package svc_test + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + + gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1" + userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" + provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" + "github.com/google/uuid" + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + "github.com/prometheus/client_golang/prometheus" + "github.com/stretchr/testify/mock" + + libregraph "github.com/opencloud-eu/libre-graph-api-go" + revactx "github.com/opencloud-eu/reva/v2/pkg/ctx" + "github.com/opencloud-eu/reva/v2/pkg/events" + "github.com/opencloud-eu/reva/v2/pkg/rgrpc/status" + cs3mocks "github.com/opencloud-eu/reva/v2/tests/cs3mocks/mocks" + + "github.com/opencloud-eu/opencloud/pkg/log" + "github.com/opencloud-eu/opencloud/pkg/shared" + "github.com/opencloud-eu/opencloud/services/graph/mocks" + "github.com/opencloud-eu/opencloud/services/graph/pkg/config/defaults" + identitymocks "github.com/opencloud-eu/opencloud/services/graph/pkg/identity/mocks" + "github.com/opencloud-eu/opencloud/services/graph/pkg/metrics" + service "github.com/opencloud-eu/opencloud/services/graph/pkg/service/v0" +) + +var _ = Describe("UnassignTags", func() { + var ( + svc service.Service + gatewayClient *cs3mocks.GatewayAPIClient + eventsPublisher *mocks.Publisher + tape *httptest.ResponseRecorder + + // the resource that loses the tags, with new random IDs for each test + storageID, spaceID, itemID string + resourceID string + ) + + // isResource matches a reference to the resource that loses the tags + isResource := func(ref *provider.Reference) bool { + id := ref.GetResourceId() + return id.GetStorageId() == storageID && id.GetSpaceId() == spaceID && id.GetOpaqueId() == itemID + } + + // resourceHasTags lets the resource have the given tags when it is stat'ed + resourceHasTags := func(existing string) { + gatewayClient.EXPECT().Stat(mock.Anything, mock.MatchedBy(func(req *provider.StatRequest) bool { + return isResource(req.GetRef()) + })).Return(&provider.StatResponse{ + Status: status.NewOK(nil), + Info: &provider.ResourceInfo{ + Id: &provider.ResourceId{StorageId: storageID, SpaceId: spaceID, OpaqueId: itemID}, + Owner: &userpb.UserId{OpaqueId: "owner"}, + PermissionSet: &provider.ResourcePermissions{InitiateFileUpload: true}, + ArbitraryMetadata: &provider.ArbitraryMetadata{Metadata: map[string]string{"tags": existing}}, + }, + }, nil) + } + + // expectStoredTags expects the tags of the resource to be set to the given list + expectStoredTags := func(tags string) { + gatewayClient.EXPECT().SetArbitraryMetadata(mock.Anything, mock.MatchedBy(func(req *provider.SetArbitraryMetadataRequest) bool { + return isResource(req.GetRef()) && req.GetArbitraryMetadata().GetMetadata()["tags"] == tags + })).Return(&provider.SetArbitraryMetadataResponse{Status: status.NewOK(nil)}, nil) + } + + // expectEvent expects a TagsRemoved event for the resource with the given + // tags, and lets publishing it return err + expectEvent := func(tags string, err error) { + eventsPublisher.EXPECT().Publish(mock.Anything, mock.MatchedBy(func(ev events.TagsRemoved) bool { + return ev.Tags == tags && isResource(ev.Ref) && ev.Executant.GetOpaqueId() == "executant" + }), mock.Anything).Return(err) + } + + // unassignTags asks to remove the given tags from the resource + unassignTags := func(tags ...string) { + body, err := json.Marshal(libregraph.TagUnassignment{ResourceId: resourceID, Tags: tags}) + Expect(err).ToNot(HaveOccurred()) + ctx := revactx.ContextSetUser(context.Background(), &userpb.User{Id: &userpb.UserId{OpaqueId: "executant"}}) + r := httptest.NewRequest(http.MethodDelete, "/graph/v1.0/extensions/org.libregraph/tags", bytes.NewReader(body)).WithContext(ctx) + svc.UnassignTags(tape, r) + } + + BeforeEach(func() { + storageID, spaceID, itemID = uuid.NewString(), uuid.NewString(), uuid.NewString() + resourceID = storageID + "$" + spaceID + "!" + itemID + + // both mocks fail the test on calls that weren't expected, and on + // expected calls that didn't happen + gatewayClient = cs3mocks.NewGatewayAPIClient(GinkgoT()) + eventsPublisher = mocks.NewPublisher(GinkgoT()) + tape = httptest.NewRecorder() + + cfg := defaults.FullDefaultConfig() + cfg.Identity.LDAP.CACert = "" // skip the startup checks, these tests don't use LDAP + cfg.TokenManager.JWTSecret = "loremipsum" + cfg.Commons = &shared.Commons{} + cfg.GRPCClientTLS = &shared.GRPCClientTLS{} + + logger := log.NewLogger() + metrics, _ := metrics.New(prometheus.NewRegistry(), &logger, func([]string) (string, string) { return "", "" }) + gatewaySelector := mocks.NewSelectable[gateway.GatewayAPIClient](GinkgoT()) + gatewaySelector.EXPECT().Next().Return(gatewayClient, nil).Maybe() + + var err error + svc, err = service.NewService( + service.Config(cfg), + service.Metrics(metrics), + service.WithIdentityBackend(&identitymocks.Backend{}), + service.WithGatewaySelector(gatewaySelector), + service.EventsPublisher(eventsPublisher), + ) + Expect(err).ToNot(HaveOccurred()) + }) + + It("removes a tag the resource has", func() { + resourceHasTags("a,b") + expectStoredTags("b") + expectEvent("a", nil) + unassignTags("a") + Expect(tape.Code).To(Equal(http.StatusOK)) + }) + + It("succeeds for a tag the resource doesn't have, without changing it, and still sends the event", func() { + resourceHasTags("a,b") + // no SetArbitraryMetadata expected: the mock fails the test if it is called + expectEvent("x", nil) + unassignTags("x") + Expect(tape.Code).To(Equal(http.StatusOK)) + }) + + It("succeeds for a resource without any tags", func() { + resourceHasTags("") + expectEvent("x", nil) + unassignTags("x") + Expect(tape.Code).To(Equal(http.StatusOK)) + }) + + It("removes the tags the resource has, and sends the event for all requested tags", func() { + resourceHasTags("a,b,c") + expectStoredTags("b") + expectEvent("a,x,c", nil) + unassignTags("a", "x", "c") + Expect(tape.Code).To(Equal(http.StatusOK)) + }) + + It("rejects a request without tags", func() { + // no gateway call and no event expected + unassignTags() + Expect(tape.Code).To(Equal(http.StatusBadRequest)) + }) + + It("sends no event if the tags can't be stored", func() { + resourceHasTags("a,b") + gatewayClient.EXPECT().SetArbitraryMetadata(mock.Anything, mock.Anything). + Return(&provider.SetArbitraryMetadataResponse{Status: status.NewInternal(context.Background(), "failure")}, nil) + unassignTags("a") + Expect(tape.Code).To(Equal(http.StatusInternalServerError)) + }) + + It("keeps the removal if the event can't be sent", func() { + resourceHasTags("a,b") + expectStoredTags("b") + expectEvent("a", errors.New("no connection to the event bus")) + unassignTags("a") + Expect(tape.Code).To(Equal(http.StatusOK)) + }) +}) diff --git a/tests/acceptance/features/apiSpaces/tag.feature b/tests/acceptance/features/apiSpaces/tag.feature index 814bb8e9db..8b31f5fc63 100644 --- a/tests/acceptance/features/apiSpaces/tag.feature +++ b/tests/acceptance/features/apiSpaces/tag.feature @@ -190,6 +190,22 @@ Feature: Tag | oc:tags | development | + Scenario: user removes a tag that the folder doesn't have + Given user "Alice" has created the following tags for folder "folderMain" of the space "use-tag": + | folderTag | + | marketing | + When user "Alice" removes the following tags for folder "folderMain" of space "use-tag": + | development | + Then the HTTP status code should be "200" + When user "Alice" lists all available tags via the Graph API + Then the HTTP status code should be "200" + And the response should contain following tags: + | folderTag | + | marketing | + And the response should not contain following tags: + | development | + + Scenario: user lists tags after deleting some folder tags Given user "Alice" has created the following tags for folder "folderMain" of the space "use-tag": | folderTag | From 2bb40b631b9a887e6e6c99d987244224a09608d9 Mon Sep 17 00:00:00 2001 From: Pascal Bleser Date: Thu, 12 Nov 2026 23:28:45 +0100 Subject: [PATCH 2/2] fix(graph): reject empty tags and report only removed tags on unassign Three follow-ups to the idempotent tag unassignment: - A request whose tags are all empty, e.g. [""] or [","], is rejected with 400 again. The tags are now split and cleaned up the same way as the stored ones before checking that there are any. - The TagsRemoved event lists only the tags that were actually removed, and is empty when the resource had none of them. It is still sent in that case, so that search reads the resource again. Search, the only consumer, uses only the reference of the event. - A locked resource is answered with 423, like assigning tags does, instead of 500. Assisted-by: Claude Code:claude-opus-5-5 --- services/graph/pkg/service/v0/tags.go | 23 ++++++++++-- .../pkg/service/v0/tags_unassign_test.go | 37 +++++++++++++++---- 2 files changed, 49 insertions(+), 11 deletions(-) diff --git a/services/graph/pkg/service/v0/tags.go b/services/graph/pkg/service/v0/tags.go index 27a71725a3..ecbe11ae07 100644 --- a/services/graph/pkg/service/v0/tags.go +++ b/services/graph/pkg/service/v0/tags.go @@ -161,11 +161,15 @@ func (g Graph) UnassignTags(w http.ResponseWriter, r *http.Request) { return } + // The requested tags, split and cleaned up the same way as the stored ones, + // so that e.g. [""] or [","] count as no tags at all. + requested := tags.New(unassignment.Tags...).AsSlice() + // A request without any tags is treated as malformed. That is a choice: // as it asks to remove nothing, succeeding with 200 or 204 would be // defensible too, but an empty list is more likely a client bug than // intended. - if len(unassignment.Tags) == 0 { + if len(requested) == 0 { errorcode.InvalidRequest.Render(w, r, http.StatusBadRequest, "no tags in tag unassignment request") return } @@ -228,7 +232,13 @@ func (g Graph) UnassignTags(w http.ResponseWriter, r *http.Request) { // is the same, and the event below still goes out, so that the search // index drops tags it may have although the resource doesn't. allTags := tags.New(currentTags) - if allTags.Remove(unassignment.Tags...) { + removed := make([]string, 0, len(requested)) + for _, tag := range requested { + if allTags.Remove(tag) { + removed = append(removed, tag) + } + } + if len(removed) > 0 { resp, err := client.SetArbitraryMetadata(ctx, &provider.SetArbitraryMetadataRequest{ Ref: &provider.Reference{ResourceId: &rid}, ArbitraryMetadata: &provider.ArbitraryMetadata{ @@ -239,14 +249,21 @@ func (g Graph) UnassignTags(w http.ResponseWriter, r *http.Request) { }) if err != nil || resp.GetStatus().GetCode() != rpc.Code_CODE_OK { logger.Error().Err(err).Interface("status", resp.GetStatus()).Msg("error setting tags") + if resp.GetStatus().GetCode() == rpc.Code_CODE_LOCKED { + errorcode.InvalidRequest.Render(w, r, http.StatusLocked, "file is locked") + return + } w.WriteHeader(http.StatusInternalServerError) return } } if g.eventsPublisher != nil { + // Tags lists only the tags that were actually removed, and is empty + // when the resource had none of them. The event is sent in that case + // too, so that consumers such as search read the resource again. ev := events.TagsRemoved{ - Tags: strings.Join(unassignment.Tags, ","), + Tags: strings.Join(removed, ","), Ref: &provider.Reference{ ResourceId: &rid, Path: ".", diff --git a/services/graph/pkg/service/v0/tags_unassign_test.go b/services/graph/pkg/service/v0/tags_unassign_test.go index 21b6fe3127..1d8d5805e7 100644 --- a/services/graph/pkg/service/v0/tags_unassign_test.go +++ b/services/graph/pkg/service/v0/tags_unassign_test.go @@ -132,32 +132,45 @@ var _ = Describe("UnassignTags", func() { It("succeeds for a tag the resource doesn't have, without changing it, and still sends the event", func() { resourceHasTags("a,b") // no SetArbitraryMetadata expected: the mock fails the test if it is called - expectEvent("x", nil) + expectEvent("", nil) unassignTags("x") Expect(tape.Code).To(Equal(http.StatusOK)) }) It("succeeds for a resource without any tags", func() { resourceHasTags("") - expectEvent("x", nil) + expectEvent("", nil) unassignTags("x") Expect(tape.Code).To(Equal(http.StatusOK)) }) - It("removes the tags the resource has, and sends the event for all requested tags", func() { + It("removes the tags the resource has, and sends the event only for those", func() { resourceHasTags("a,b,c") expectStoredTags("b") - expectEvent("a,x,c", nil) + expectEvent("a,c", nil) unassignTags("a", "x", "c") Expect(tape.Code).To(Equal(http.StatusOK)) }) - It("rejects a request without tags", func() { - // no gateway call and no event expected - unassignTags() - Expect(tape.Code).To(Equal(http.StatusBadRequest)) + It("lists a tag requested twice only once in the event", func() { + resourceHasTags("a,b") + expectStoredTags("b") + expectEvent("a", nil) + unassignTags("a", "a,a") + Expect(tape.Code).To(Equal(http.StatusOK)) }) + DescribeTable("rejects a request without tags", + func(tags ...string) { + // no gateway call and no event expected + unassignTags(tags...) + Expect(tape.Code).To(Equal(http.StatusBadRequest)) + }, + Entry("no tags at all"), + Entry("an empty tag", ""), + Entry("only separators", ","), + ) + It("sends no event if the tags can't be stored", func() { resourceHasTags("a,b") gatewayClient.EXPECT().SetArbitraryMetadata(mock.Anything, mock.Anything). @@ -166,6 +179,14 @@ var _ = Describe("UnassignTags", func() { Expect(tape.Code).To(Equal(http.StatusInternalServerError)) }) + It("answers 423 and sends no event if the resource is locked", func() { + resourceHasTags("a,b") + gatewayClient.EXPECT().SetArbitraryMetadata(mock.Anything, mock.Anything). + Return(&provider.SetArbitraryMetadataResponse{Status: status.NewLocked(context.Background(), "locked")}, nil) + unassignTags("a") + Expect(tape.Code).To(Equal(http.StatusLocked)) + }) + It("keeps the removal if the event can't be sent", func() { resourceHasTags("a,b") expectStoredTags("b")