Merge pull request #10863 from AnomalRoil/fix/fuzz/48208

fix: types: error out on decoding BlockMsg with extraneous data
This commit is contained in:
Aayush Rajasekaran 2023-05-29 16:58:41 -04:00 committed by GitHub
commit b76b5ef4b7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 46 additions and 2 deletions

View File

@ -2,6 +2,7 @@ package types
import (
"bytes"
"fmt"
"github.com/ipfs/go-cid"
)
@ -14,10 +15,13 @@ type BlockMsg struct {
func DecodeBlockMsg(b []byte) (*BlockMsg, error) {
var bm BlockMsg
if err := bm.UnmarshalCBOR(bytes.NewReader(b)); err != nil {
data := bytes.NewReader(b)
if err := bm.UnmarshalCBOR(data); err != nil {
return nil, err
}
if l := data.Len(); l != 0 {
return nil, fmt.Errorf("extraneous data in BlockMsg CBOR encoding: got %d unexpected bytes", l)
}
return &bm, nil
}

View File

@ -0,0 +1,40 @@
package types
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestDecodeBlockMsg(t *testing.T) {
type args struct {
b []byte
}
tests := []struct {
name string
data []byte
want *BlockMsg
wantErr bool
}{
{"decode empty BlockMsg with extra data at the end", []byte{0x83, 0xf6, 0x80, 0x80, 0x20}, nil, true},
{"decode valid empty BlockMsg", []byte{0x83, 0xf6, 0x80, 0x80}, new(BlockMsg), false},
{"decode invalid cbor", []byte{0x83, 0xf6, 0x80}, nil, true},
}
for _, tt := range tests {
data := tt.data
want := tt.want
wantErr := tt.wantErr
t.Run(tt.name, func(t *testing.T) {
got, err := DecodeBlockMsg(data)
if wantErr {
assert.Errorf(t, err, "DecodeBlockMsg(%x)", data)
return
}
assert.NoErrorf(t, err, "DecodeBlockMsg(%x)", data)
assert.Equalf(t, want, got, "DecodeBlockMsg(%x)", data)
serialized, err := got.Serialize()
assert.NoErrorf(t, err, "DecodeBlockMsg(%x)", data)
assert.Equalf(t, serialized, data, "DecodeBlockMsg(%x)", data)
})
}
}