Skip to content

Commit

Permalink
Fix non-string map keys check in decode_dag_cbor (#17)
Browse files Browse the repository at this point in the history
  • Loading branch information
MarshalX committed Mar 1, 2024
1 parent 4975730 commit 10e190d
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
10 changes: 9 additions & 1 deletion pytests/test_dag_cbor.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,22 @@ def _dag_cbor_roundtrip(benchmark, data) -> None:
assert obj == decoded, f'{obj} != {decoded}'


def test_dag_cbor_decode_duplicate_keys() -> None:
def test_dag_cbor_decode_duplicate_keys_error() -> None:
with pytest.raises(ValueError) as exc_info:
# {"abc": 1, "abc": 2}
libipld.decode_dag_cbor(bytes.fromhex('a263616263016361626302'))

assert 'Duplicate keys are not allowed' in str(exc_info.value)


def test_dag_cbor_decode_non_string_key_error() -> None:
with pytest.raises(ValueError) as exc_info:
# {1:2}
libipld.decode_dag_cbor(bytes.fromhex('A10102'))

assert 'Map keys must be strings' in str(exc_info.value)


@pytest.mark.parametrize('data', load_data_fixtures(_ROUNDTRIP_DATA_DIR), ids=lambda data: data[0])
def test_dag_cbor_encode(benchmark, data) -> None:
_dag_cbor_encode(benchmark, data)
Expand Down
10 changes: 9 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,15 @@ fn decode_dag_cbor_to_pyobject<R: Read + Seek>(py: Python, r: &mut R, deep: usiz
let len = decode_len(decode::read_uint(r, major)?)?;
let dict = PyDict::new(py);
for _ in 0..len {
let key = decode_dag_cbor_to_pyobject(py, r, deep + 1)?;
// DAG-CBOR keys are always strings
let key_major = decode::read_major(r)?;
if key_major.kind() != MajorKind::TextString {
return Err(anyhow::anyhow!("Map keys must be strings"));
}

let key_len = decode::read_uint(r, key_major)?;
let key = decode::read_str(r, key_len)?.to_object(py);

let value = decode_dag_cbor_to_pyobject(py, r, deep + 1)?;

if dict.get_item(&key)?.is_some() {
Expand Down

0 comments on commit 10e190d

Please sign in to comment.