Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
28 changes: 28 additions & 0 deletions bindform.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down
43 changes: 41 additions & 2 deletions bindform_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
})
Expand Down