segmentio/encoding

Decoder hangs when decoding invalid json

Closed this issue · 4 comments

func TestHangingDecoder(t *testing.T) {
	b := []byte(`{
	"userId": "blah",
	}`)

	d := NewDecoder(bytes.NewReader(b))

	var a struct {
		UserId string `json:"userId"`
	}
	err := d.Decode(&a)
	if err == nil {
		t.Fatal("should have errored")
	}
}

This test hangs on master. Light on details for now, will add more when I have them.

Looks like it's an issue in Decoder. It works fine with Unmarshal:

// this works
func TestHangingDecoder(t *testing.T) {
	b := []byte(`{
	"userId": "blah",
	}`)
	var a struct {
		UserId string `json:"userId"`
	}
	err := Unmarshal(b, &a)
	if err == nil {
		t.Fatal("should have errored")
	}
}

This is also not valid JSON, the trailing comma is forbidden (I'll work on a fix).

yeah, it's the point

Decode() should error in this scenario. Not hang :)

I think the issue comes from

encoding/json/json.go

Lines 285 to 289 in 4980b2f

v, r, err = parseValue(dec.remain)
if err == nil {
dec.remain = skipSpaces(r)
return
}

We continue looping even though parseValue returns an error.