From 92347e6f61455a6bb8c079ff279d6a75879b2b32 Mon Sep 17 00:00:00 2001 From: Marcin Romaszewicz Date: Sat, 5 Dec 2026 08:41:12 -0800 Subject: [PATCH] feat: add BindFormAllowsArrayGaps to accept sparse form arrays Since #204 BindForm refuses an indexed array whose indexes skip some, such as topic[0]=a&topic[2]=c, because an array is as long as its highest index says and a form which may skip indexes can ask for one of any length with a single key. A client which sends such forms worked before that change. The package variable BindFormAllowsArrayGaps, off by default, restores the old reading: the array is as long as its highest index says, and the elements the form does not name are left at their zero value. Setting it gives the bound up again, so a request decides how much memory the server allocates. The documentation says so, and that it belongs only where every client is trusted or such forms are refused before they reach BindForm. Only an index as strconv.Itoa writes it names an element, with or without the setting. Co-Authored-By: Claude Fable 5.2 --- README.md | 18 ++++++++++++++++++ bindform.go | 28 ++++++++++++++++++++++++++++ bindform_test.go | 43 +++++++++++++++++++++++++++++++++++++++++-- 3 files changed, 87 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 6346e23..97438bc 100644 --- a/README.md +++ b/README.md @@ -280,3 +280,21 @@ Indexes have to run from `0` without a gap. `topic[0]=a&topic[2]=c` is an error, rather than an array with an empty element in the middle. An array is as long as its highest index says, so this keeps what a request can make the server allocate in proportion to what it sends. + +Before v1.10.0 a gap was accepted, and the elements a form did not name were +left empty. To accept such forms again, set this once during program +initialization (it is not safe to mutate concurrently with in-flight +requests): + +```go +func init() { + runtime.BindFormAllowsArrayGaps = true +} +``` + +> [!WARNING] +> With this set, a request decides how much memory the server allocates. The +> 20-byte body `topic[4000000]=a` allocates four million elements, and a larger +> index allocates more, until the process runs out of memory. Anyone who can +> send a form body can do that. Set it only where every client is trusted, or +> where something in front of `BindForm` has already refused such a form. diff --git a/bindform.go b/bindform.go index f7bcb09..5ece642 100644 --- a/bindform.go +++ b/bindform.go @@ -55,6 +55,27 @@ func formFieldTag(f reflect.StructField) string { // not safe to mutate concurrently with in-flight requests. var MarshalFormIgnoresTextMarshaler bool +// BindFormAllowsArrayGaps restores how BindForm read an array whose indexes +// skip some, as in topic[0]=a&topic[2]=c, before it learned to refuse one. +// +// By default the indexes of an array have to run from zero without a gap, and +// a form which skips one is an error. When this is set, the array is as long +// as its highest index says, and the elements the form does not name are left +// at their zero value: the form above binds as ["a", "", "c"]. +// +// Setting it lets a request decide how much memory the server allocates. A +// single short key such as topic[4000000]=a makes BindForm allocate four +// million elements, and a larger index allocates more, until the process runs +// out of memory. Anyone who can send a form body can do that, so set this +// only where every client is trusted, or where something in front of BindForm +// has already refused such a form. +// +// Only an index as strconv.Itoa writes it names an element either way. +// +// Like DefaultQueryEncoder, set it once during program initialization; it is +// not safe to mutate concurrently with in-flight requests. +var BindFormAllowsArrayGaps bool + type RequestBodyEncoding struct { ContentType string Style string @@ -471,16 +492,23 @@ func bindFormImpl(v reflect.Value, data *formData, name string) (bool, error) { // its highest index says, so a form which could skip indexes could ask for // an array of any length with a single key. Without gaps the array is never // longer than the number of keys which were sent for it. +// BindFormAllowsArrayGaps gives that up, and takes the highest index at its +// word. // // Only an index as strconv.Itoa writes it counts. Any other key, such as // name[-1] or name[01], is not read as an element. func indexedElementsCount(data *formData, name string) (int, error) { indexes := map[int]struct{}{} + highest := -1 for str := range data.bracketed(name) { if idx, err := strconv.Atoi(str); err == nil && idx >= 0 && strconv.Itoa(idx) == str { indexes[idx] = struct{}{} + highest = max(highest, idx) } } + if BindFormAllowsArrayGaps { + return highest + 1, nil + } for i := range len(indexes) { if _, ok := indexes[i]; !ok { return 0, fmt.Errorf("form array '%s' has no element at index %d: indexes must run from 0 without gaps", name, i) diff --git a/bindform_test.go b/bindform_test.go index ac49266..900f560 100644 --- a/bindform_test.go +++ b/bindform_test.go @@ -1162,9 +1162,48 @@ func TestBindFormArrayBounds(t *testing.T) { assert.ErrorContains(t, err, "'topics' has no element at index 1") }) - // Only an index written the way MarshalForm writes one names an element. + // BindFormAllowsArrayGaps takes the highest index at its word, as BindForm + // did before it refused a gap, and leaves what the form does not name at + // its zero value. + t.Run("gaps allowed", func(t *testing.T) { + BindFormAllowsArrayGaps = true + t.Cleanup(func() { BindFormAllowsArrayGaps = false }) + + got, err := bind(t, "topics[0]=a&topics[2]=c&topics=d&items[1][name]=b&tags[1]=a", nil) + require.NoError(t, err) + assert.Equal(t, []string{"a", "", "c", "d"}, got.Topics) + assert.Equal(t, &[]item{{}, {"b"}}, got.Items) + assert.Equal(t, nullable.NewNullableWithValue([]string{"", "a"}), got.Tags) + + form, err := makeMultipartFilesForm([]fileData{{field: "files[1]", filename: "a.txt", content: []byte("a")}}) + require.NoError(t, err) + var files body + require.NoError(t, BindForm(&files, form.Value, form.File, nil)) + require.Len(t, files.Files, 2) + assert.Equal(t, "a.txt", files.Files[1].Filename()) + + no := false + got, err = bind(t, "topics[0]=a&topics[2]=c", map[string]RequestBodyEncoding{"topics": {Style: "form", Explode: &no}}) + require.NoError(t, err) + assert.Equal(t, []string{"a", "", "c"}, got.Topics) + + // A form without a gap binds as it does by default. + got, err = bind(t, "items[2][name]=c&items[0][name]=a&items[1][name]=b", nil) + require.NoError(t, err) + assert.Equal(t, &[]item{{"a"}, {"b"}, {"c"}}, got.Items) + }) + + // Only an index written the way MarshalForm writes one names an element, + // with or without gaps. t.Run("keys which are not indexes", func(t *testing.T) { - got, err := bind(t, "topics[0]=a&topics[-1]=b&topics[01]=c&topics[%2B1]=d&topics[x]=e&topics[1.0]=f", nil) + const query = "topics[0]=a&topics[-1]=b&topics[01]=c&topics[%2B1]=d&topics[x]=e&topics[1.0]=f" + got, err := bind(t, query, nil) + require.NoError(t, err) + assert.Equal(t, []string{"a"}, got.Topics) + + BindFormAllowsArrayGaps = true + t.Cleanup(func() { BindFormAllowsArrayGaps = false }) + got, err = bind(t, query, nil) require.NoError(t, err) assert.Equal(t, []string{"a"}, got.Topics) })