From cfe3b1703839e0e4b0a2b92f769e720dedda70b0 Mon Sep 17 00:00:00 2001 From: Dominik Schmidt Date: Fri, 27 Nov 2026 10:57:06 +0100 Subject: [PATCH] fix(search): limit the shape of aggregation requests At most 16 aggregations and 3 bucket levels per request and 5 requests per query. The bleve collector stops at the bucket limit instead of checking after the walk, and the limit also holds for the result merged across spaces. --- services/graph/pkg/service/v0/searchquery.go | 6 ++++ .../graph/pkg/service/v0/searchquery_test.go | 9 +++++ .../search/pkg/aggregation/aggregation.go | 16 ++++++--- services/search/pkg/aggregation/validate.go | 32 ++++++++++++++--- .../search/pkg/aggregation/validate_test.go | 35 +++++++++++++++++++ services/search/pkg/bleve/aggregations.go | 15 ++++++++ services/search/pkg/bleve/backend.go | 4 +++ services/search/pkg/search/service.go | 3 ++ services/search/pkg/search/service_test.go | 25 +++++++++++++ 9 files changed, 137 insertions(+), 8 deletions(-) diff --git a/services/graph/pkg/service/v0/searchquery.go b/services/graph/pkg/service/v0/searchquery.go index 0b33ed40d6..ad93813f4c 100644 --- a/services/graph/pkg/service/v0/searchquery.go +++ b/services/graph/pkg/service/v0/searchquery.go @@ -18,6 +18,8 @@ import ( "github.com/opencloud-eu/opencloud/services/search/pkg/search" ) +const maxSearchRequests = 5 + // SearchQuery handles POST /v1beta1/search/query (MS Graph searchQuery). func (g Graph) SearchQuery(w http.ResponseWriter, r *http.Request) { var req libregraph.SearchQueryRequest @@ -31,6 +33,10 @@ func (g Graph) SearchQuery(w http.ResponseWriter, r *http.Request) { errorcode.InvalidRequest.Render(w, r, http.StatusBadRequest, "requests array must not be empty") return } + if len(req.Requests) > maxSearchRequests { + errorcode.InvalidRequest.Render(w, r, http.StatusBadRequest, fmt.Sprintf("requests array takes at most %d requests", maxSearchRequests)) + return + } if err := validateSearchExpand(r); err != nil { errorcode.InvalidRequest.Render(w, r, http.StatusBadRequest, err.Error()) diff --git a/services/graph/pkg/service/v0/searchquery_test.go b/services/graph/pkg/service/v0/searchquery_test.go index 6ccf7bb001..cf9dbaf468 100644 --- a/services/graph/pkg/service/v0/searchquery_test.go +++ b/services/graph/pkg/service/v0/searchquery_test.go @@ -8,6 +8,7 @@ import ( "fmt" "net/http" "net/http/httptest" + "strings" // ginkgo qualified: the svc package declares Context (option.go), which // would collide with a dot-import. @@ -423,6 +424,14 @@ var _ = ginkgo.Describe("SearchQuery", func() { `"aggregations": [{"field": "audio.artist", "@libre.graph.subAggregations": [{"field": "location", "@libre.graph.geohashDefinition": {"precision": 5}}]}]`, "geohashDefinition"), ) + ginkgo.It("rejects more than 5 requests with 400", func() { + one := `{"entityTypes": ["driveItem"], "query": {"queryString": "a"}}` + body := `{"requests": [` + strings.Repeat(one+",", 5) + one + `]}` + rr := postSearchQuery(graphWithoutSearch(), body) + Expect(rr.Code).To(Equal(http.StatusBadRequest), rr.Body.String()) + Expect(rr.Body.String()).To(ContainSubstring("at most 5 requests")) + }) + ginkgo.It("rejects an $expand it does not know with 400", func() { req := httptest.NewRequest(http.MethodPost, "/search/query?$expand=thumbnails,permissions", bytes.NewBufferString(searchQueryBody(`"from": 0`))) rr := httptest.NewRecorder() diff --git a/services/search/pkg/aggregation/aggregation.go b/services/search/pkg/aggregation/aggregation.go index 61cc9c0602..a2b1c215c3 100644 --- a/services/search/pkg/aggregation/aggregation.go +++ b/services/search/pkg/aggregation/aggregation.go @@ -31,16 +31,24 @@ func KindOf(opt *searchsvc.AggregationOption) Kind { return KindTerms } -// MaxBuckets is how many buckets the aggregations of one request may have in -// one space, all levels counted: the search.max_buckets default of OpenSearch, -// held on every engine. +// MaxBuckets is how many buckets the aggregations of one request may have, +// all levels counted, in one space and in the merged result: the +// search.max_buckets default of OpenSearch, held on every engine. const MaxBuckets = math.MaxUint16 +// MaxAggregations is how many aggregations one request may carry, all levels +// counted. MaxDepth is how deep buckets may nest; a metric is a leaf and adds +// no level. +const ( + MaxAggregations = 16 + MaxDepth = 3 +) + // ErrTooManyBuckets is what an engine answers beyond MaxBuckets; the service // layer turns it into a bad request. var ErrTooManyBuckets = fmt.Errorf("the aggregations have more than %d buckets, narrow the query or the aggregations", MaxBuckets) -// CheckBuckets holds the results of one space to MaxBuckets. +// CheckBuckets holds results to MaxBuckets. func CheckBuckets(results []*searchsvc.AggregationResult) error { if countBuckets(results) > MaxBuckets { return ErrTooManyBuckets diff --git a/services/search/pkg/aggregation/validate.go b/services/search/pkg/aggregation/validate.go index 9169245a5a..453702cba3 100644 --- a/services/search/pkg/aggregation/validate.go +++ b/services/search/pkg/aggregation/validate.go @@ -7,10 +7,34 @@ import ( "github.com/opencloud-eu/opencloud/services/search/pkg/mapping" ) -// ValidateOptions holds aggregations to what the index can answer: a field it -// knows, a kind that fits the type of the field. fieldType returns the mapping -// type of a field, empty for one a client may not aggregate on. +// ValidateOptions holds aggregations to MaxAggregations and MaxDepth and to +// what the index can answer: a field it knows, a kind that fits the type of +// the field. fieldType returns the mapping type of a field, empty for one a +// client may not aggregate on. func ValidateOptions(opts []*searchsvc.AggregationOption, fieldType func(string) string) error { + count, depth := shape(opts) + if count > MaxAggregations { + return fmt.Errorf("a request takes at most %d aggregations, sub-aggregations included", MaxAggregations) + } + if depth > MaxDepth { + return fmt.Errorf("aggregations nest at most %d levels deep", MaxDepth) + } + return validateOptions(opts, fieldType) +} + +func shape(opts []*searchsvc.AggregationOption) (count, depth int) { + for _, opt := range opts { + subCount, subDepth := shape(opt.GetSubAggregations()) + if KindOf(opt) != KindMetric { + subDepth++ + } + count += 1 + subCount + depth = max(depth, subDepth) + } + return count, depth +} + +func validateOptions(opts []*searchsvc.AggregationOption, fieldType func(string) string) error { for _, opt := range opts { field, t := opt.GetField(), fieldType(opt.GetField()) if t == "" { @@ -37,7 +61,7 @@ func ValidateOptions(opts []*searchsvc.AggregationOption, fieldType func(string) return err } } - if err := ValidateOptions(opt.GetSubAggregations(), fieldType); err != nil { + if err := validateOptions(opt.GetSubAggregations(), fieldType); err != nil { return err } } diff --git a/services/search/pkg/aggregation/validate_test.go b/services/search/pkg/aggregation/validate_test.go index 762180e0d9..0a02580c9b 100644 --- a/services/search/pkg/aggregation/validate_test.go +++ b/services/search/pkg/aggregation/validate_test.go @@ -67,4 +67,39 @@ var _ = Describe("ValidateOptions", func() { {Field: "audio.album", SubAggregations: []*searchsvc.AggregationOption{{Field: "photo.takenDateTime"}}}, }}), ) + + chain := func(levels int, leaf *searchsvc.AggregationOption) *searchsvc.AggregationOption { + opt := leaf + for range levels { + var subs []*searchsvc.AggregationOption + if opt != nil { + subs = append(subs, opt) + } + opt = &searchsvc.AggregationOption{Field: "audio.artist", SubAggregations: subs} + } + return opt + } + flat := func(n int) []*searchsvc.AggregationOption { + opts := make([]*searchsvc.AggregationOption, n) + for i := range opts { + opts[i] = &searchsvc.AggregationOption{Field: "audio.artist"} + } + return opts + } + + It("holds the nesting to MaxDepth, a metric adds no level", func() { + metric := &searchsvc.AggregationOption{Field: "audio.year", MetricDefinition: sum} + Expect(aggregation.MaxDepth).To(Equal(3)) + Expect(aggregation.ValidateOptions([]*searchsvc.AggregationOption{chain(3, nil)}, fieldTypes)).To(Succeed()) + Expect(aggregation.ValidateOptions([]*searchsvc.AggregationOption{chain(3, metric)}, fieldTypes)).To(Succeed()) + Expect(aggregation.ValidateOptions([]*searchsvc.AggregationOption{chain(4, nil)}, fieldTypes)).To(MatchError(ContainSubstring("3 levels"))) + }) + + It("holds a request to MaxAggregations, all levels counted", func() { + Expect(aggregation.MaxAggregations).To(Equal(16)) + Expect(aggregation.ValidateOptions(flat(16), fieldTypes)).To(Succeed()) + Expect(aggregation.ValidateOptions(flat(17), fieldTypes)).To(MatchError(ContainSubstring("16 aggregations"))) + nested := append(flat(14), chain(3, nil)) + Expect(aggregation.ValidateOptions(nested, fieldTypes)).To(MatchError(ContainSubstring("16 aggregations"))) + }) }) diff --git a/services/search/pkg/bleve/aggregations.go b/services/search/pkg/bleve/aggregations.go index f4948cb856..ccf23ea1a9 100644 --- a/services/search/pkg/bleve/aggregations.go +++ b/services/search/pkg/bleve/aggregations.go @@ -97,6 +97,8 @@ type aggCollector struct { fields map[string]*fieldValues fieldNames []string roots []*aggRoot + buckets int + overflow bool } type aggRoot struct { @@ -174,6 +176,9 @@ func (c *aggCollector) collect(dvr index.DocValueReader, d *bleveSearch.Document for _, root := range c.roots { c.fold(root.acc, root.level) } + if c.overflow { + return aggregation.ErrTooManyBuckets + } return nil } @@ -233,6 +238,16 @@ func (c *aggCollector) fold(a *bucketAcc, l *aggLevel) { } func (c *aggCollector) foldBucket(a *bucketAcc, l *aggLevel, key string) { + if c.overflow { + return + } + if _, ok := a.counts[key]; !ok { + if c.buckets == aggregation.MaxBuckets { + c.overflow = true + return + } + c.buckets++ + } a.counts[key]++ if len(l.children) == 0 { return diff --git a/services/search/pkg/bleve/backend.go b/services/search/pkg/bleve/backend.go index 7521ecc641..53d390b643 100644 --- a/services/search/pkg/bleve/backend.go +++ b/services/search/pkg/bleve/backend.go @@ -2,6 +2,7 @@ package bleve import ( "context" + "errors" "fmt" "math" "sync" @@ -133,6 +134,9 @@ func (b *Backend) Search(ctx context.Context, sir *search.IndexQuery) (*search.I bleveReq.Fields = []string{"*"} res, err := b.index.SearchInContext(ctx, bleveReq) + if errors.Is(err, aggregation.ErrTooManyBuckets) { + return nil, errtypes.BadRequest(err.Error()) + } if err != nil { return nil, err } diff --git a/services/search/pkg/search/service.go b/services/search/pkg/search/service.go index d70eb37641..a9e057aade 100644 --- a/services/search/pkg/search/service.go +++ b/services/search/pkg/search/service.go @@ -365,6 +365,9 @@ func (s *Service) Search(ctx context.Context, req *searchsvc.SearchRequest) (*se aggregations = aggregation.Merge(req.GetAggregations(), aggregations, res.Aggregations) } aggregation.Finalize(req.GetAggregations(), aggregations) + if err := aggregation.CheckBuckets(aggregations); err != nil { + return nil, errtypes.BadRequest(err.Error()) + } // compile one sorted list of matches from all spaces and apply from/limit if needed sort.Sort(matches) diff --git a/services/search/pkg/search/service_test.go b/services/search/pkg/search/service_test.go index 32a332c94c..368caffd70 100644 --- a/services/search/pkg/search/service_test.go +++ b/services/search/pkg/search/service_test.go @@ -958,6 +958,31 @@ var _ = Describe("Searchprovider", func() { }) }) + Context("with two personal spaces whose buckets exceed the limit together", func() { + artists := func(space string) []*searchsvc.Bucket { + buckets := make([]*searchsvc.Bucket, 40000) + for i := range buckets { + buckets[i] = &searchsvc.Bucket{Key: fmt.Sprintf("%s-%d", space, i), Count: 1} + } + return buckets + } + + It("refuses the merged result as a bad request", func() { + listsSpacesAB() + for _, space := range []string{"a", "b"} { + searchOfSpace(space).Return(&search.IndexResult{ + Aggregations: []*searchsvc.AggregationResult{{Field: "audio.artist", Buckets: artists(space)}}, + }, nil) + } + _, err := s.Search(ctx, &searchsvc.SearchRequest{ + Query: "mediatype:audio", + Aggregations: []*searchsvc.AggregationOption{{Field: "audio.artist"}}, + }) + Expect(err).To(BeAssignableToTypeOf(errtypes.BadRequest(""))) + Expect(err).To(MatchError(ContainSubstring("65535 buckets"))) + }) + }) + Context("with two personal spaces returning matches of the same score", func() { match := func(space, name string) *searchmsg.Match { return &searchmsg.Match{Score: 1, Entity: &searchmsg.Entity{