From 2ea716aea4d3fda7579dd1cf1ad0a503e817ecf5 Mon Sep 17 00:00:00 2001 From: Gaurav Soni Date: Tue, 4 Aug 2026 14:29:11 +0200 Subject: [PATCH] [OCISDEV-492] Space image not uploaded if larger than 7MB (#12701) fix(graph): [OCISDEV-492] reject space images too large to be rendered Setting a space image larger than the thumbnails service accepts appeared to succeed but never changed the space image. Uploading the file and assigning it as the space image are two separate requests, and both completed successfully, so clients reported success. Only a later preview request, which the assigning client never observes, was rejected because the image exceeded THUMBNAILS_MAX_INPUT_IMAGE_FILE_SIZE. As space images are rendered exclusively as thumbnails, the image was not merely degraded, it was invisible with no error anywhere in the UI. The graph service now stats the file when a space image is assigned and rejects the request with 413 Request Entity Too Large instead of storing a reference which cannot be displayed. The previous space image is left untouched. The limit is read from the new GRAPH_MAX_IMAGE_FILE_SIZE setting, which defaults to the value of THUMBNAILS_MAX_INPUT_IMAGE_FILE_SIZE so that a single setting keeps both services in agreement. A limit of zero disables the check. Space descriptions (readme) are not affected. --- .../fix-space-image-size-validation.md | 20 +++ services/graph/README.md | 10 ++ services/graph/pkg/config/config.go | 3 +- .../pkg/config/defaults/defaultconfig.go | 3 +- services/graph/pkg/service/v0/drives.go | 49 +++++- services/graph/pkg/service/v0/graph.go | 1 + services/graph/pkg/service/v0/graph_test.go | 140 ++++++++++++++++++ services/graph/pkg/service/v0/service.go | 9 ++ services/thumbnails/README.md | 6 + 9 files changed, 237 insertions(+), 4 deletions(-) create mode 100644 changelog/unreleased/fix-space-image-size-validation.md diff --git a/changelog/unreleased/fix-space-image-size-validation.md b/changelog/unreleased/fix-space-image-size-validation.md new file mode 100644 index 00000000000..1635bc2ed12 --- /dev/null +++ b/changelog/unreleased/fix-space-image-size-validation.md @@ -0,0 +1,20 @@ +Bugfix: Reject space images which are too large to be rendered + +Setting a space image larger than the thumbnails service accepts appeared to +succeed but never changed the space image. Uploading the file and assigning it +as the space image are two separate requests, and both completed successfully, +so clients reported success. Only a later preview request, which the assigning +client never observes, was rejected because the image exceeded +`THUMBNAILS_MAX_INPUT_IMAGE_FILE_SIZE`. As space images are rendered +exclusively as thumbnails, the image was not merely degraded, it was invisible +with no error anywhere in the UI. + +The graph service now checks the file size when a space image is assigned and +rejects the request with `413 Request Entity Too Large` instead of storing a +reference which cannot be displayed. The previous space image is left +untouched. The limit is read from the new `GRAPH_MAX_IMAGE_FILE_SIZE` setting, +which defaults to `50MB` and must be less than or equal to +`THUMBNAILS_MAX_INPUT_IMAGE_FILE_SIZE`. Space descriptions (`readme`) are not +affected. + +https://github.com/owncloud/ocis/pull/12701 diff --git a/services/graph/README.md b/services/graph/README.md index 9597451686f..8e49a818e11 100644 --- a/services/graph/README.md +++ b/services/graph/README.md @@ -59,6 +59,16 @@ is based on the [OData Specification](https://docs.oasis-open.org/odata/odata/v4 See the [Libre Graph API](https://owncloud.dev/libre-graph-api/#/users/ListUsers) for examples on the filters supported when querying users. +## Space Image File Size + +A space can have an image, set by assigning a file in the space's `.space` folder via `PATCH /graph/v1beta1/drives/{drive-id}`. Space images are rendered exclusively as thumbnails and there is no raw download fallback, which means an image that the `thumbnails` service refuses to process cannot be displayed at all. + +The graph service therefore rejects an assignment with `413/Request Entity Too Large` if the referenced file exceeds `GRAPH_MAX_IMAGE_FILE_SIZE`, defaulting to `50MB`. Without this check, assigning a too large image would succeed but the image would silently never appear. A previously set space image is left unchanged when an assignment is rejected. Set the value to `0` to not limit the file size. + +This limit is independent of `THUMBNAILS_MAX_INPUT_IMAGE_FILE_SIZE` of the `thumbnails` service, which is the upper bound for any image that can be rendered at all. A deployment can set a stricter limit for space images than for thumbnails in general, but `GRAPH_MAX_IMAGE_FILE_SIZE` must be less than or equal to `THUMBNAILS_MAX_INPUT_IMAGE_FILE_SIZE`. Both default to `50MB`. If the graph limit is set higher, images between the two values are accepted as a space image but cannot be rendered. + +Only the file size is enforced. The independent dimension limits of the `thumbnails` service, `THUMBNAILS_MAX_INPUT_WIDTH` and `THUMBNAILS_MAX_INPUT_HEIGHT`, are not checked here, because image dimensions cannot be determined without downloading and decoding the image. A small image with very large dimensions can therefore still be accepted and still fail to render. + ## Caching The `graph` service can use a configured store via `GRAPH_CACHE_STORE`. Possible stores are: diff --git a/services/graph/pkg/config/config.go b/services/graph/pkg/config/config.go index eb4cee3b045..1cfb0518d50 100644 --- a/services/graph/pkg/config/config.go +++ b/services/graph/pkg/config/config.go @@ -182,7 +182,8 @@ type ServiceAccount struct { } type Validation struct { - MaxTagLength int `yaml:"max_tag_length" env:"OCIS_MAX_TAG_LENGTH" desc:"Define the maximum tag length. Defaults to 100 if not set. Set to 0 to not limit the tag length. Changes only impact the validation of new tags." introductionVersion:"7.2.0"` + MaxTagLength int `yaml:"max_tag_length" env:"OCIS_MAX_TAG_LENGTH" desc:"Define the maximum tag length. Defaults to 100 if not set. Set to 0 to not limit the tag length. Changes only impact the validation of new tags." introductionVersion:"7.2.0"` + MaxImageFileSize string `yaml:"max_image_file_size" env:"GRAPH_MAX_IMAGE_FILE_SIZE" desc:"The maximum file size of an image which can be set as a space image. Must be less than or equal to 'THUMBNAILS_MAX_INPUT_IMAGE_FILE_SIZE' of the thumbnails service, otherwise images between the two values are accepted but cannot be rendered. Usable common abbreviations: [KB, KiB, MB, MiB, GB, GiB, TB, TiB, PB, PiB, EB, EiB], example: 2GB. Set to 0 to not limit the file size." introductionVersion:"8.2.0"` } // MultiInstanceConfig holds configuration for multi-instance-ocis diff --git a/services/graph/pkg/config/defaults/defaultconfig.go b/services/graph/pkg/config/defaults/defaultconfig.go index ccb39673cef..17c851ad34a 100644 --- a/services/graph/pkg/config/defaults/defaultconfig.go +++ b/services/graph/pkg/config/defaults/defaultconfig.go @@ -135,7 +135,8 @@ func DefaultConfig() *config.Config { AvailableRoles: nil, // will be populated with defaults in EnsureDefaults }, Validation: config.Validation{ - MaxTagLength: 100, + MaxTagLength: 100, + MaxImageFileSize: "50MB", }, } } diff --git a/services/graph/pkg/service/v0/drives.go b/services/graph/pkg/service/v0/drives.go index d80d5a11fa5..255486f3c92 100644 --- a/services/graph/pkg/service/v0/drives.go +++ b/services/graph/pkg/service/v0/drives.go @@ -58,8 +58,34 @@ var ( // ErrForbiddenCharacter is thrown when the spacename contains an invalid character ErrForbiddenCharacter = fmt.Errorf("spacenames must not contain %v", _invalidSpaceNameCharacters) + + errSpaceImageTooLarge = errors.New("space image is too large") ) +func (g Graph) checkSpaceImageFileSize(ctx context.Context, gatewayClient gateway.GatewayAPIClient, fileID string) error { + if g.maxImageFileSize == 0 { + return nil + } + + resourceID, err := storagespace.ParseID(fileID) + if err != nil { + return errorcode.New(errorcode.InvalidRequest, fmt.Sprintf("invalid space image id: %v", err)) + } + + statResponse, err := gatewayClient.Stat(ctx, &storageprovider.StatRequest{ + Ref: &storageprovider.Reference{ResourceId: &resourceID}, + }) + if err := errorcode.FromStat(statResponse, err); err != nil { + return err + } + + if size := statResponse.GetInfo().GetSize(); size > g.maxImageFileSize { + return fmt.Errorf("%w: %d bytes exceeds the maximum of %d bytes", errSpaceImageTooLarge, size, g.maxImageFileSize) + } + + return nil +} + // GetDrives serves as a factory method that returns the appropriate // http.Handler function based on the specified API version. func (g Graph) GetDrives(version APIVersion) http.HandlerFunc { @@ -560,9 +586,28 @@ func (g Graph) updateDrive(w http.ResponseWriter, r *http.Request, apiVersion AP } for _, special := range drive.Special { - if special.Id != nil { - updateSpaceRequest.StorageSpace.Opaque = utils.AppendPlainToOpaque(updateSpaceRequest.StorageSpace.Opaque, *special.SpecialFolder.Name, *special.Id) + if special.Id == nil { + continue } + + // A space image which exceeds the thumbnailer's maximum input file size + // can be stored but never rendered, and the web UI has no raw-download + // fallback, so it would silently stay invisible. Reject it here instead. + if special.SpecialFolder.GetName() == SpaceImageSpecialFolderName { + if err := g.checkSpaceImageFileSize(r.Context(), gatewayClient, *special.Id); err != nil { + logger.Debug().Err(err).Str("fileID", *special.Id).Msg("could not update drive: space image rejected") + if errors.Is(err, errSpaceImageTooLarge) { + // errorcode.InvalidRequest renders as 400 by default, but the + // specific problem here is the size of the payload. + errorcode.InvalidRequest.Render(w, r, http.StatusRequestEntityTooLarge, err.Error()) + return + } + errorcode.RenderError(w, r, err) + return + } + } + + updateSpaceRequest.StorageSpace.Opaque = utils.AppendPlainToOpaque(updateSpaceRequest.StorageSpace.Opaque, *special.SpecialFolder.Name, *special.Id) } if _, ok := drive.GetNameOk(); ok { diff --git a/services/graph/pkg/service/v0/graph.go b/services/graph/pkg/service/v0/graph.go index 6ceebe3a962..8bbf90c0a84 100644 --- a/services/graph/pkg/service/v0/graph.go +++ b/services/graph/pkg/service/v0/graph.go @@ -68,6 +68,7 @@ type Graph struct { keycloakClient keycloak.Client historyClient ehsvc.EventHistoryService traceProvider trace.TracerProvider + maxImageFileSize uint64 } // ServeHTTP implements the Service interface. diff --git a/services/graph/pkg/service/v0/graph_test.go b/services/graph/pkg/service/v0/graph_test.go index d6f31ba2aa6..047163ecc37 100644 --- a/services/graph/pkg/service/v0/graph_test.go +++ b/services/graph/pkg/service/v0/graph_test.go @@ -92,6 +92,16 @@ var _ = Describe("Graph", func() { It("returns a service", func() { Expect(svc).ToNot(BeNil()) }) + + It("fails when the maximum image file size is not parseable", func() { + cfg.Validation.MaxImageFileSize = "notasize" + _, err := service.NewService( + service.Config(cfg), + service.WithGatewaySelector(gatewaySelector), + ) + Expect(err).To(HaveOccurred()) + Expect(err.Error()).To(ContainSubstring("max_image_file_size")) + }) }) Describe("Drives", func() { @@ -1203,6 +1213,136 @@ var _ = Describe("Graph", func() { return req.StorageSpace.Id.OpaqueId == "spaceid" && req.StorageSpace.Quota.QuotaMaxBytes == uint64(1000) })) }) + + Describe("setting the space image", func() { + var ( + imageFileID = "spaceid$spaceid!imageid" + + spaceImageUpdate = func() []byte { + drive := libregraph.NewDrive("thename") + drive.SetSpecial([]libregraph.DriveItem{{ + Id: &imageFileID, + SpecialFolder: &libregraph.SpecialFolder{Name: libregraph.PtrString("image")}, + }}) + driveJson, err := json.Marshal(drive) + Expect(err).ToNot(HaveOccurred()) + return driveJson + } + + patchDrive = func(body []byte) { + r := httptest.NewRequest(http.MethodPatch, "/graph/v1.0/drives/{driveID}/", bytes.NewBuffer(body)) + rctx := chi.NewRouteContext() + rctx.URLParams.Add("driveID", "spaceid") + r = r.WithContext(context.WithValue(revactx.ContextSetUser(ctx, currentUser), chi.RouteCtxKey, rctx)) + svc.UpdateDrive(rr, r) + } + + onStatReturnSize = func(size uint64) { + gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(&provider.StatResponse{ + Status: status.NewOK(ctx), + Info: &provider.ResourceInfo{Size: size}, + }, nil) + } + + onUpdateStorageSpaceOK = func() { + gatewayClient.On("UpdateStorageSpace", mock.Anything, mock.Anything).Return(func(_ context.Context, req *provider.UpdateStorageSpaceRequest, _ ...grpc.CallOption) *provider.UpdateStorageSpaceResponse { + return &provider.UpdateStorageSpaceResponse{ + Status: status.NewOK(ctx), + StorageSpace: req.StorageSpace, + } + }, nil) + gatewayClient.On("GetPath", mock.Anything, mock.Anything).Return(&provider.GetPathResponse{ + Status: status.NewOK(ctx), + Path: "/.space/image.png", + }, nil) + } + + expectStoredSpecial = func(name, fileID string) { + gatewayClient.AssertCalled(GinkgoT(), "UpdateStorageSpace", mock.Anything, mock.MatchedBy(func(req *provider.UpdateStorageSpaceRequest) bool { + return utils.ReadPlainFromOpaque(req.StorageSpace.Opaque, name) == fileID + })) + } + ) + + setMaxImageFileSize := func(size string) { + cfg.Validation.MaxImageFileSize = size + var err error + svc, err = service.NewService( + service.Config(cfg), + service.WithGatewaySelector(gatewaySelector), + service.EventsPublisher(&eventsPublisher), + service.PermissionService(&permissionService), + ) + Expect(err).ToNot(HaveOccurred()) + } + + BeforeEach(func() { + setMaxImageFileSize("1KB") + }) + + It("rejects an image larger than the configured maximum and stores nothing", func() { + onUpdateStorageSpaceOK() + onStatReturnSize(2048) + + patchDrive(spaceImageUpdate()) + + Expect(rr.Code).To(Equal(http.StatusRequestEntityTooLarge)) + gatewayClient.AssertNotCalled(GinkgoT(), "UpdateStorageSpace", mock.Anything, mock.Anything) + }) + + It("accepts an image of exactly the configured maximum", func() { + onUpdateStorageSpaceOK() + onStatReturnSize(1000) // 1KB, as bytesize uses decimal units + + patchDrive(spaceImageUpdate()) + + Expect(rr.Code).To(Equal(http.StatusOK)) + expectStoredSpecial("image", imageFileID) + }) + + It("accepts any size when the maximum is set to zero", func() { + setMaxImageFileSize("0") + onUpdateStorageSpaceOK() + onStatReturnSize(100 * 1024 * 1024) + + patchDrive(spaceImageUpdate()) + + Expect(rr.Code).To(Equal(http.StatusOK)) + expectStoredSpecial("image", imageFileID) + }) + + It("does not store the image when the size could not be determined", func() { + onUpdateStorageSpaceOK() + gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(&provider.StatResponse{ + Status: status.NewInternal(ctx, "stat failed"), + }, nil) + + patchDrive(spaceImageUpdate()) + + Expect(rr.Code).ToNot(Equal(http.StatusOK)) + Expect(rr.Code).ToNot(Equal(http.StatusRequestEntityTooLarge)) + gatewayClient.AssertNotCalled(GinkgoT(), "UpdateStorageSpace", mock.Anything, mock.Anything) + }) + + It("does not restrict the size of the space readme", func() { + onUpdateStorageSpaceOK() + onStatReturnSize(100 * 1024 * 1024) + + readmeFileID := "spaceid$spaceid!readmeid" + drive := libregraph.NewDrive("thename") + drive.SetSpecial([]libregraph.DriveItem{{ + Id: &readmeFileID, + SpecialFolder: &libregraph.SpecialFolder{Name: libregraph.PtrString("readme")}, + }}) + driveJson, err := json.Marshal(drive) + Expect(err).ToNot(HaveOccurred()) + + patchDrive(driveJson) + + Expect(rr.Code).To(Equal(http.StatusOK)) + expectStoredSpecial("readme", readmeFileID) + }) + }) }) Describe("Delete a drive", func() { diff --git a/services/graph/pkg/service/v0/service.go b/services/graph/pkg/service/v0/service.go index ee0a0605006..2bd51535fb4 100644 --- a/services/graph/pkg/service/v0/service.go +++ b/services/graph/pkg/service/v0/service.go @@ -18,6 +18,7 @@ import ( microstore "go-micro.dev/v4/store" "github.com/owncloud/reva/v2/pkg/autoprop" + "github.com/owncloud/reva/v2/pkg/bytesize" "github.com/owncloud/reva/v2/pkg/events" "github.com/owncloud/reva/v2/pkg/rgrpc/todo/pool" "github.com/owncloud/reva/v2/pkg/store" @@ -168,6 +169,14 @@ func NewService(opts ...Option) (Graph, error) { //nolint:maintidx valueService: options.ValueService, } + if raw := options.Config.Validation.MaxImageFileSize; raw != "" { + maxImageFileSize, err := bytesize.Parse(raw) + if err != nil { + return svc, fmt.Errorf("could not parse validation.max_image_file_size %q: %w", raw, err) + } + svc.maxImageFileSize = maxImageFileSize.Bytes() + } + if err := setIdentityBackends(options, &svc); err != nil { return svc, err } diff --git a/services/thumbnails/README.md b/services/thumbnails/README.md index ecbcc4a060a..6f16fd0fdfa 100644 --- a/services/thumbnails/README.md +++ b/services/thumbnails/README.md @@ -86,6 +86,12 @@ As of now, there is no automated thumbnail deletion. This is especially true whe Since source files need to be loaded into memory when generating thumbnails, large source files could potentially crash this service if there is insufficient memory available. For bigger instances when using container orchestration deployment methods, this service can be dedicated to its own server(s) with more memory. To have more control over memory (and CPU) consumption the maximum number of concurrent requests can be limited by setting the environment variable `THUMBNAILS_MAX_CONCURRENT_REQUESTS`. The default value is 0 which does not apply any restrictions to the number of concurrent requests. As soon as the number of concurrent requests is reached any further request will be responded with `429/Too Many Requests` and the client can retry at a later point in time. +## Maximum Input Image File Size + +The maximum file size of an image that will be processed is limited by `THUMBNAILS_MAX_INPUT_IMAGE_FILE_SIZE`, defaulting to `50MB`. A request for a thumbnail of a larger image is responded with `403/Forbidden`. + +This value is the upper bound for what can be displayed anywhere in the instance. The `graph` service has its own, independent limit for space images, `GRAPH_MAX_IMAGE_FILE_SIZE`, which must be less than or equal to this one. See the `graph` service documentation for details. + ## Thumbnails and SecureView If a resource is shared using SecureView, the share receiver will get a 403 (forbidden) response when requesting a thumbnail. The requesting client needs to decide what to show and usually a placeholder thumbnail is used.