Skip to content

Commit 78d1cfc

Browse files
authored
Fix handling of concatenated objects / CBOR sequence (#65)
1 parent 389ebfa commit 78d1cfc

2 files changed

Lines changed: 31 additions & 2 deletions

File tree

pytests/test_dag_cbor.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,3 +227,22 @@ def test_dag_cbor_decode_negative_infinity_f32_error() -> None:
227227
libipld.decode_dag_cbor(bytes.fromhex('faff800000'))
228228

229229
assert 'number out of range for f32' in str(exc_info.value).lower()
230+
231+
232+
def test_dag_cbor_decode_cbor_sequence_error() -> None:
233+
# 0000 - two CBOR zeros (CBOR sequence), invalid in DAG-CBOR
234+
with pytest.raises(ValueError) as exc_info:
235+
libipld.decode_dag_cbor(bytes.fromhex('0000'))
236+
237+
assert 'multiple objects' in str(exc_info.value).lower()
238+
239+
240+
def test_decode_dag_cbor_multi() -> None:
241+
# 0000 - two CBOR zeros (CBOR sequence), valid only for decode_dag_cbor_multi
242+
dag_cbor = bytes.fromhex('0000')
243+
decoded = libipld.decode_dag_cbor_multi(dag_cbor)
244+
245+
assert isinstance(decoded, list)
246+
assert len(decoded) == 2
247+
assert decoded[0] == 0
248+
assert decoded[1] == 0

src/lib.rs

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -481,9 +481,19 @@ pub fn decode_car<'py>(py: Python<'py>, data: &[u8]) -> PyResult<(PyObject, Boun
481481

482482
#[pyfunction]
483483
pub fn decode_dag_cbor(py: Python, data: &[u8]) -> PyResult<PyObject> {
484-
let py_object = decode_dag_cbor_to_pyobject(py, &mut BufReader::new(Cursor::new(data)), 0);
484+
let mut reader = BufReader::new(Cursor::new(data));
485+
let py_object = decode_dag_cbor_to_pyobject(py, &mut reader, 0);
485486
if let Ok(py_object) = py_object {
486-
Ok(py_object)
487+
// check for any remaining data in the reader
488+
let mut buf = [0u8; 1];
489+
match reader.read(&mut buf) {
490+
Ok(0) => Ok(py_object), // EOF
491+
Err(_) => Ok(py_object), // EOF
492+
Ok(_) => Err(get_err(
493+
"Failed to decode DAG-CBOR",
494+
"Invalid DAG-CBOR: contains multiple objects (CBOR sequence)".to_string()
495+
)),
496+
}
487497
} else {
488498
let err = get_err(
489499
"Failed to decode DAG-CBOR",

0 commit comments

Comments
 (0)