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.
This commit is contained in:
Dominik Schmidt committed 2026-11-27 15:51:55 +01:00
1 parent f228110fdf
commit cfe3b17038
9 files changed
+137 -8

No files matched your search

@@ -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())
@@ -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()
+12 -4
View File
@@ -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
+28 -4
View File
@@ -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
}
}
@@ -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")))
})
})
+15
View File
@@ -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
+4
View File
@@ -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
}
+3
View File
@@ -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)
@@ -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{