diff --git a/pkg/config/defaults/tags.go b/pkg/config/defaults/tags.go new file mode 100644 index 0000000000..edcbd4fa61 --- /dev/null +++ b/pkg/config/defaults/tags.go @@ -0,0 +1,8 @@ +package defaults + +// MaxTagLength is the default maximum length of a single tag, in characters. +// The graph service rejects longer tags, and the frontend service announces the +// limit to clients as the graph.tags.max_tag_length capability: both read +// OC_MAX_TAG_LENGTH, and both must default to the same value, so that clients +// are told the limit the server actually enforces. +const MaxTagLength = 100 diff --git a/services/frontend/pkg/config/config.go b/services/frontend/pkg/config/config.go index 366b6c876f..a8274fcd6e 100644 --- a/services/frontend/pkg/config/config.go +++ b/services/frontend/pkg/config/config.go @@ -58,6 +58,7 @@ type Config struct { ServiceAccount ServiceAccount `yaml:"service_account"` PasswordPolicy PasswordPolicy `yaml:"password_policy"` + Validation Validation `yaml:"validation"` ConfigurableNotifications bool `yaml:"configurable_notifications" env:"FRONTEND_CONFIGURABLE_NOTIFICATIONS" desc:"Allow configuring notifications via web client." introductionVersion:"1.0.0"` @@ -236,3 +237,8 @@ type Groupware struct { type Thumbnails struct { AdditionalSourceTypes []string `yaml:"additional_source_types" env:"OC_THUMBNAILS_ADDITIONAL_SOURCE_TYPES;FRONTEND_THUMBNAILS_ADDITIONAL_SOURCE_TYPES" desc:"Additional mime types oc:has-preview is answered with 1 for, the same list the webdav service attempts previews for. The types the build ships are included; this only adds to them." introductionVersion:"9.0.0"` } + +// Validation holds limits that are announced to clients as capabilities. +type Validation struct { + MaxTagLength int `yaml:"max_tag_length" env:"OC_MAX_TAG_LENGTH" desc:"The maximum length of a single tag, in characters. Longer tags are rejected when they are assigned; tags that already exist are not affected. Clients are told the limit through the graph.tags.max_tag_length capability, which is why the graph and frontend services share this setting: when setting it in the configuration files of the services instead, set it to the same value for both. Set to 0 to not limit the length of tags." introductionVersion:"%%NEXT%%"` +} diff --git a/services/frontend/pkg/config/defaults/defaultconfig.go b/services/frontend/pkg/config/defaults/defaultconfig.go index d652301957..2e7ace9345 100644 --- a/services/frontend/pkg/config/defaults/defaultconfig.go +++ b/services/frontend/pkg/config/defaults/defaultconfig.go @@ -3,6 +3,7 @@ package defaults import ( "time" + ocdefaults "github.com/opencloud-eu/opencloud/pkg/config/defaults" "github.com/opencloud-eu/opencloud/pkg/shared" "github.com/opencloud-eu/opencloud/pkg/structs" "github.com/opencloud-eu/opencloud/services/frontend/pkg/config" @@ -146,6 +147,9 @@ func DefaultConfig() *config.Config { MinDigits: 1, MinSpecialCharacters: 1, }, + Validation: config.Validation{ + MaxTagLength: ocdefaults.MaxTagLength, + }, Groupware: config.Groupware{ Enabled: false, }, diff --git a/services/frontend/pkg/revaconfig/config.go b/services/frontend/pkg/revaconfig/config.go index 989661adce..8d33f00d48 100644 --- a/services/frontend/pkg/revaconfig/config.go +++ b/services/frontend/pkg/revaconfig/config.go @@ -227,6 +227,9 @@ func FrontendConfigFromStruct(cfg *config.Config, logger log.Logger) (map[string "change_password_self_disabled": changePasswordDisabled, "edit_login_allowed_disabled": cfg.EditLoginAllowedDisabled, }, + "tags": map[string]any{ + "max_tag_length": cfg.Validation.MaxTagLength, + }, }, "checksums": map[string]any{ "supported_types": cfg.Checksums.SupportedTypes, diff --git a/services/frontend/pkg/revaconfig/config_test.go b/services/frontend/pkg/revaconfig/config_test.go index df8656e4d8..9a41e64f2b 100644 --- a/services/frontend/pkg/revaconfig/config_test.go +++ b/services/frontend/pkg/revaconfig/config_test.go @@ -47,3 +47,19 @@ func dig(t *testing.T, m map[string]any, keys ...string) map[string]any { } return m } + +func TestMaxTagLengthCapability(t *testing.T) { + for _, maxTagLength := range []int{100, 20, 0} { + cfg := defaults.FullDefaultConfig() + cfg.Commons = &shared.Commons{} + if maxTagLength != 100 { + cfg.Validation.MaxTagLength = maxTagLength + } + + rcfg, err := FrontendConfigFromStruct(cfg, log.NopLogger()) + require.NoError(t, err) + + got := dig(t, rcfg, "http", "services", "ocs", "capabilities", "capabilities", "graph", "tags")["max_tag_length"] + require.Equal(t, maxTagLength, got) + } +} diff --git a/services/graph/pkg/config/config.go b/services/graph/pkg/config/config.go index 39df259d9f..5c78426051 100644 --- a/services/graph/pkg/config/config.go +++ b/services/graph/pkg/config/config.go @@ -39,6 +39,8 @@ type Config struct { Keycloak Keycloak `yaml:"keycloak"` ServiceAccount ServiceAccount `yaml:"service_account"` + Validation Validation `yaml:"validation"` + MachineAuthAPIKey string `yaml:"machine_auth_api_key" env:"OC_MACHINE_AUTH_API_KEY;GRAPH_MACHINE_AUTH_API_KEY" desc:"Machine auth API key used to validate internal requests necessary for the access to resources from other services." introductionVersion:"7.5.0" mask:"password"` Context context.Context `yaml:"-"` @@ -220,3 +222,8 @@ type Thumbnails struct { // graph doesn't accept a space image no thumbnail can be made of SpaceImageMaxInputImageFileSize string `yaml:"space_image_max_input_image_file_size" env:"OC_THUMBNAILS_MAX_INPUT_IMAGE_FILE_SIZE;THUMBNAILS_MAX_INPUT_IMAGE_FILE_SIZE;OC_SPACE_IMAGE_THUMBNAILS_MAX_INPUT_IMAGE_FILE_SIZE" desc:"The maximum file size of an image that can be set as the image of a space. A larger one is refused with HTTP 413, because no thumbnail can be made of it, and space images are only shown as thumbnails. Usable common abbreviations: [KB, KiB, MB, MiB, GB, GiB], example: 50MB. An empty value means unlimited." introductionVersion:"9.2.0"` } + +// Validation holds limits that requests to the graph service are checked against. +type Validation struct { + MaxTagLength int `yaml:"max_tag_length" env:"OC_MAX_TAG_LENGTH" desc:"The maximum length of a single tag, in characters. Longer tags are rejected when they are assigned; tags that already exist are not affected. Clients are told the limit through the graph.tags.max_tag_length capability, which is why the graph and frontend services share this setting: when setting it in the configuration files of the services instead, set it to the same value for both. Set to 0 to not limit the length of tags." introductionVersion:"%%NEXT%%"` +} diff --git a/services/graph/pkg/config/defaults/defaultconfig.go b/services/graph/pkg/config/defaults/defaultconfig.go index daccf5068d..4fe8285d30 100644 --- a/services/graph/pkg/config/defaults/defaultconfig.go +++ b/services/graph/pkg/config/defaults/defaultconfig.go @@ -153,6 +153,9 @@ func DefaultConfig() *config.Config { UnifiedRoles: config.UnifiedRoles{ AvailableRoles: nil, // will be populated with defaults in EnsureDefaults }, + Validation: config.Validation{ + MaxTagLength: ocdefaults.MaxTagLength, + }, Metadata: config.Metadata{ GatewayAddress: "eu.opencloud.api.storage-system", StorageAddress: "eu.opencloud.api.storage-system", diff --git a/services/graph/pkg/service/v0/tags.go b/services/graph/pkg/service/v0/tags.go index 0f84f46555..e3bce42daf 100644 --- a/services/graph/pkg/service/v0/tags.go +++ b/services/graph/pkg/service/v0/tags.go @@ -109,7 +109,10 @@ func (g Graph) AssignTags(w http.ResponseWriter, r *http.Request) { } allTags := tags.New(currentTags) - if !allTags.Add(assignment.Tags...) { + if added, err := allTags.AddValidated(tags.MaxLengthValidator(g.config.Validation.MaxTagLength), assignment.Tags...); err != nil { + errorcode.InvalidRequest.Render(w, r, http.StatusBadRequest, err.Error()) + return + } else if !added { errorcode.InvalidRequest.Render(w, r, http.StatusBadRequest, "no new tags in createtagsrequest or maximum reached") return } diff --git a/services/graph/pkg/service/v0/tags_assign_test.go b/services/graph/pkg/service/v0/tags_assign_test.go new file mode 100644 index 0000000000..a6ccd77624 --- /dev/null +++ b/services/graph/pkg/service/v0/tags_assign_test.go @@ -0,0 +1,145 @@ +package svc_test + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + + gateway "github.com/cs3org/go-cs3apis/cs3/gateway/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/stretchr/testify/mock" + + libregraph "github.com/opencloud-eu/libre-graph-api-go" + "github.com/opencloud-eu/reva/v3/pkg/rgrpc/status" + cs3mocks "github.com/opencloud-eu/reva/v3/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" + "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" + "github.com/prometheus/client_golang/prometheus" +) + +var _ = Describe("AssignTags", func() { + var ( + cfg *config.Config + gatewayClient *cs3mocks.GatewayAPIClient + tape *httptest.ResponseRecorder + + // the resource that gets the tags, with new random IDs for each test + storageID, spaceID, itemID string + resourceID string + ) + + // isResource matches a reference to the resource that gets the tags + isResource := func(ref *provider.Reference) bool { + id := ref.GetResourceId() + return id.GetStorageId() == storageID && id.GetSpaceId() == spaceID && id.GetOpaqueId() == itemID + } + + // assignTags sends a tag assignment for the resource, which already has the + // given tags, to a graph service with the current configuration + assignTags := func(existing string, tags ...string) { + 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() + + svc, err := service.NewService( + service.Config(cfg), + service.Metrics(metrics), + service.WithIdentityBackend(&identitymocks.Backend{}), + service.WithGatewaySelector(gatewaySelector), + ) + Expect(err).ToNot(HaveOccurred()) + + 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}, + PermissionSet: &provider.ResourcePermissions{InitiateFileUpload: true}, + ArbitraryMetadata: &provider.ArbitraryMetadata{Metadata: map[string]string{"tags": existing}}, + }, + }, nil) + + body, err := json.Marshal(libregraph.TagAssignment{ResourceId: resourceID, Tags: tags}) + Expect(err).ToNot(HaveOccurred()) + svc.AssignTags(tape, httptest.NewRequest(http.MethodPut, "/graph/v1.0/extensions/org.libregraph/tags", bytes.NewReader(body))) + } + + // 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) + } + + BeforeEach(func() { + storageID, spaceID, itemID = uuid.NewString(), uuid.NewString(), uuid.NewString() + resourceID = storageID + "$" + spaceID + "!" + itemID + + gatewayClient = cs3mocks.NewGatewayAPIClient(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{} + cfg.Validation.MaxTagLength = 5 + }) + + It("limits tags to 100 characters by default", func() { + Expect(defaults.FullDefaultConfig().Validation.MaxTagLength).To(Equal(100)) + }) + + It("stores tags up to the maximum length", func() { + expectStoredTags("abcde,new,old") + assignTags("old", "abcde", "new") + Expect(tape.Code).To(Equal(http.StatusOK)) + }) + + It("rejects the whole assignment if a tag is too long, and stores nothing", func() { + // no SetArbitraryMetadata expected: the mock fails the test if it is called + assignTags("old", "ok", "abcdef") + Expect(tape.Code).To(Equal(http.StatusBadRequest)) + Expect(tape.Body.String()).To(ContainSubstring(`\"abcdef\"`)) + Expect(tape.Body.String()).ToNot(ContainSubstring(`\"ok\"`)) + }) + + It("counts characters, not bytes", func() { + expectStoredTags("äöüßé") + assignTags("", "äöüßé") + Expect(tape.Code).To(Equal(http.StatusOK)) + }) + + It("doesn't count the whitespace around a tag", func() { + expectStoredTags("abcde") + assignTags("", " abcde ") + Expect(tape.Code).To(Equal(http.StatusOK)) + }) + + It("doesn't limit the length if the maximum is 0", func() { + long := strings.Repeat("x", 1000) + cfg.Validation.MaxTagLength = 0 + expectStoredTags(long) + assignTags("", long) + Expect(tape.Code).To(Equal(http.StatusOK)) + }) + + It("still rejects an assignment without new tags", func() { + assignTags("abc", "abc") + Expect(tape.Code).To(Equal(http.StatusBadRequest)) + }) +}) diff --git a/tests/acceptance/features/apiSpaces/tag.feature b/tests/acceptance/features/apiSpaces/tag.feature index 8b31f5fc63..47199a76fb 100644 --- a/tests/acceptance/features/apiSpaces/tag.feature +++ b/tests/acceptance/features/apiSpaces/tag.feature @@ -319,3 +319,18 @@ Feature: Tag | finance | | hr | | qa | + + + Scenario: user tries to create a tag that is longer than the maximum tag length + When user "Alice" creates the following tags for folder "folderMain" of space "use-tag": + | bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb0123456789 | + Then the HTTP status code should be "400" + When user "Alice" creates the following tags for folder "folderMain" of space "use-tag": + | aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0123456789 | + 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: + | aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0123456789 | + And the response should not contain following tags: + | bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb0123456789 |