Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(dagcbor): don't accept trailing bytes #386

Merged
merged 2 commits into from
Mar 16, 2022
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: 17 additions & 1 deletion codec/dagcbor/unmarshal.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (
var (
ErrInvalidMultibase = errors.New("invalid multibase on IPLD link")
ErrAllocationBudgetExceeded = errors.New("message structure demanded too many resources to process")
ErrTrailingBytes = errors.New("unexpected content after end of cbor object")
)

const (
Expand Down Expand Up @@ -49,9 +50,24 @@ func (cfg DecodeOptions) Decode(na datamodel.NodeAssembler, r io.Reader) error {
return na2.DecodeDagCbor(r)
}
// Okay, generic builder path.
return Unmarshal(na, cbor.NewDecoder(cbor.DecodeOptions{
err := Unmarshal(na, cbor.NewDecoder(cbor.DecodeOptions{
CoerceUndefToNull: true,
}, r), cfg)

if err != nil {
return err
}

var buf [1]byte
_, err = io.ReadFull(r, buf[:])
switch err {
case io.EOF:
return nil
case nil:
return ErrTrailingBytes
default:
return err
}
}

// Future work: we would like to remove the Unmarshal function,
Expand Down
6 changes: 6 additions & 0 deletions codec/dagcbor/unmarshal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,4 +49,10 @@ func TestFunBlocks(t *testing.T) {
qt.Assert(t, err, qt.IsNil)
qt.Assert(t, nb.Build().Kind(), qt.Equals, datamodel.Kind_Null)
})
t.Run("extra bytes", func(t *testing.T) {
buf := strings.NewReader("\xa0\x00")
nb := basicnode.Prototype.Any.NewBuilder()
err := Decode(nb, buf)
qt.Assert(t, err, qt.Equals, ErrTrailingBytes)
})
}
4 changes: 1 addition & 3 deletions node/bindnode/fuzz_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -238,9 +238,7 @@ func FuzzBindnodeViaDagCBOR(f *testing.F) {
t.Logf("decode successful: %#v", reflect.ValueOf(bindnode.Unwrap(node)).Elem().Interface())
reenc := marshalDagCBOR(t, node)
if !bytes.Equal(reenc, nodeDagCBOR) {
// TODO: reenable this once the dagcbor codec rejects non-canonical
// inputs like "00" and "a000", "0" and "a0" respectively.
// t.Errorf("node reencoded as %q rather than %q", reenc, nodeDagCBOR)
t.Errorf("node reencoded as %q rather than %q", reenc, nodeDagCBOR)
}
t.Logf("re-encode successful: %q", reenc)
}
Expand Down