mitchellh / mapstructure

Go library for decoding generic map values into native Go structures and vice versa.
https://gist.github.com/mitchellh/90029601268e59a29e64e55bab1c5bdc
MIT License
7.93k stars 677 forks source link

panic when Decode's input is array and output is a slice #264

Closed suzuki-shunsuke closed 2 years ago

suzuki-shunsuke commented 2 years ago

I found the problem when I investigated the issue of Terraform AWS Provider.

ref. https://github.com/hashicorp/terraform-provider-aws/issues/22312#issuecomment-999566173

Panic occurs when an array is passed as Decode's input.

How to reproduce

You can reproduce the problem by passing an array as Decode's input.

https://go.dev/play/p/BMxes5mbumY

panic: reflect: call of reflect.Value.IsNil on array Value

goroutine 1 [running]:
reflect.Value.IsNil(...)
    /usr/local/go-faketime/src/reflect/value.go:1427
github.com/mitchellh/mapstructure.(*Decoder).decodeSlice(0xc000120018, {0x0, 0x0}, {0x4b4aa0, 0xc00010a4b0}, {0x4b2fa0, 0xc00011a030, 0x203000})
    /tmp/gopath2282395412/pkg/mod/github.com/mitchellh/mapstructure@v1.4.3/mapstructure.go:1091 +0xbfe
github.com/mitchellh/mapstructure.(*Decoder).decode(0xc000120018, {0x0, 0xc000126001}, {0x4b4aa0, 0xc00010a4b0}, {0x4b2fa0, 0xc00011a030, 0x48})
    /tmp/gopath2282395412/pkg/mod/github.com/mitchellh/mapstructure@v1.4.3/mapstructure.go:469 +0x3ff
github.com/mitchellh/mapstructure.(*Decoder).Decode(0xc000120018, {0x4b4aa0, 0xc00010a4b0})
    /tmp/gopath2282395412/pkg/mod/github.com/mitchellh/mapstructure@v1.4.3/mapstructure.go:398 +0xd8
github.com/mitchellh/mapstructure.Decode({0x4b4aa0, 0xc00010a4b0}, {0x4b0be0, 0xc00011a030})
    /tmp/gopath2282395412/pkg/mod/github.com/mitchellh/mapstructure@v1.4.3/mapstructure.go:302 +0x91
main.core()
    /tmp/sandbox2579048427/prog.go:19 +0x65
main.main()
    /tmp/sandbox2579048427/prog.go:11 +0x19

Program exited.

And you can fix the problem by changing the input type from array to slice.

https://go.dev/play/p/xrfz5X8RJis

suzuki-shunsuke commented 2 years ago

https://github.com/mitchellh/mapstructure/blob/b9b99d7d59762a5b2a43df840adc318b2fa229ee/mapstructure.go#L1091

https://pkg.go.dev/reflect#Value.IsNil

The argument must be a chan, func, interface, map, pointer, or slice value; if it is not, IsNil panics.

suzuki-shunsuke commented 2 years ago

I have sent a pull request to fix the issue. https://github.com/mitchellh/mapstructure/pull/265