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

Commit 8176c13

Browse files
rvaggvmx
authored andcommitted
fix: reject CBOR data with extraneous back-to-back encoded data
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
1 parent 242576f commit 8176c13

File tree

2 files changed

+15
-2
lines changed

2 files changed

+15
-2
lines changed

src/util.js

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -153,9 +153,14 @@ exports.deserialize = (data) => {
153153
throw new Error('Data is too large to deserialize with current decoder')
154154
}
155155

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

158-
return deserialized
163+
return all[0]
159164
}
160165

161166
/**

test/util.spec.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,4 +122,12 @@ describe('util', () => {
122122
expect(dagCBOR.util.deserialize(s1)).to.be.eql({ data: bytes })
123123
expect(dagCBOR.util.deserialize(s2)).to.be.eql({ data: bytes })
124124
})
125+
126+
it('reject extraneous, but valid CBOR data after initial top-level object', () => {
127+
expect(() =>
128+
// two top-level CBOR objects, the original and a single uint=0, valid if using
129+
// CBOR in streaming mode, not valid here
130+
dagCBOR.util.deserialize(Buffer.concat([serializedObj, Buffer.alloc(1)]))
131+
).to.throw(Error, 'Extraneous CBOR data found beyond initial top-level object')
132+
})
125133
})

0 commit comments

Comments
 (0)