Skip to content
This repository has been archived by the owner on Aug 11, 2021. It is now read-only.

Commit

Permalink
fix: reject CBOR data with extraneous back-to-back encoded data
Browse files Browse the repository at this point in the history
The streaming form of CBOR (3.1) may use back-to-back top-level objects without
an explicit container and borc will decode this without failure.
`decodeFirst()` will only return the first of these but additional data may
exist but be hidden.

Ref: dignifiedquire/borc#47 (comment)
Ref: ipld/specs#268
  • Loading branch information
rvagg authored and vmx committed Jun 12, 2020
1 parent 242576f commit 8176c13
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
9 changes: 7 additions & 2 deletions src/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -153,9 +153,14 @@ exports.deserialize = (data) => {
throw new Error('Data is too large to deserialize with current decoder')
}

const deserialized = decoder.decodeFirst(data)
// borc will decode back-to-back objects into an implicit top-level array, we
// strictly want to only see a single explicit top-level object
const all = decoder.decodeAll(data)
if (all.length !== 1) {
throw new Error('Extraneous CBOR data found beyond initial top-level object')
}

return deserialized
return all[0]
}

/**
Expand Down
8 changes: 8 additions & 0 deletions test/util.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -122,4 +122,12 @@ describe('util', () => {
expect(dagCBOR.util.deserialize(s1)).to.be.eql({ data: bytes })
expect(dagCBOR.util.deserialize(s2)).to.be.eql({ data: bytes })
})

it('reject extraneous, but valid CBOR data after initial top-level object', () => {
expect(() =>
// two top-level CBOR objects, the original and a single uint=0, valid if using
// CBOR in streaming mode, not valid here
dagCBOR.util.deserialize(Buffer.concat([serializedObj, Buffer.alloc(1)]))
).to.throw(Error, 'Extraneous CBOR data found beyond initial top-level object')
})
})

0 comments on commit 8176c13

Please sign in to comment.